Javascript search by tag. Javascript and jquery selecting an element by class (class attribute). So we write the script from scratch

💖 Do you like it? Share the link with your friends

Within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

Note: The matching is done using depth-first pre-order traversal of the document"s nodes starting with the first element in the document"s markup and iterating through sequential nodes by order of the number of child nodes.

Syntax element = document.querySelector(selectors); Parameters selectors A DOMString containing one or more selectors to match. This string must be a valid CSS selector string; if it isn't, a SYNTAX_ERR exception is thrown. See Locating DOM elements using selectors for more about selectors and how to manage them.

Note: Characters that are not part of standard CSS syntax must be escaped using a backslash character. Since JavaScript also uses backslash escaping, be especially careful when writing string literals using these characters. See for more information.

Return value Exceptions SYNTAX_ERR The syntax of the specified selectors is invalid. Usage notes

If the specified selector matches an ID that is incorrectly used more than once in the document, the first element with that ID is returned.

Escaping special characters

To match against an ID or selectors that do not follow standard CSS syntax (by using a colon or space inappropriately, for example), you must escape the character with a backslash (" \ "). As the backslash is also an escape character in JavaScript, if you are entering a literal string, you must escape it twice(once for the JavaScript string, and another time for querySelector()):

console.log("#foo\bar"); // "#fooar" (\b is the backspace control character) document.querySelector("#foo\bar"); // Does not match anything console.log("#foo\\bar"); // "#foo\bar" console.log("#foo\\\\bar"); // "#foo\\bar" document.querySelector("#foo\\\\bar"); // Match the first div document.querySelector("#foo:bar"); // Does not match anything document.querySelector("#foo\\:bar"); // Match the second div

Examples Finding the first element matching a class

In this example, the first element in the document with the class " myclass " is returned:

Var el = document.querySelector(".myclass");

A more complex selector

Selectors can also be really powerful, as demonstrated in the following example. Here, the first element with the name "login" () located inside a whose class is "user-panel main" () in the document is returned:

Var el = document.querySelector("div.user-panel.main input");

Specifications Specification Status Comment
DOM
The definition of "document.querySelector()" in that specification.
Living Standard
Browser compatibility

The compatibility table on this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Desktop Mobile Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung InternetquerySelector
Chrome Full support 1Edge Full support 12Firefox Full support 3.5IE Full support 8Opera Full support 10Safari Full support 3.2WebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support 10.1Safari iOS Full support 3.2Samsung Internet Android ?
Legend Full support Full support Compatibility unknown Compatibility unknown

In addition to the fact that we can select elements on web pages by their id, we can also select elements by their class attribute.

The task is also very common. When I write my scripts, I have to use this selector very often.

Let's assume we have the following code on the page.

Block contents.

The task is simple, you need to select an element with the class class="elem" and perform some actions with it using Javascript.

Let's look at several options on how to do this.

Option 1. Use Javascript method getElementsByClassName.

If you do not use any additional libraries, you can access an element using the getElementsByClassName(“class_name”) method.

For example, in relation to source code, you can add the following lines of code.

Block content. alert(document.getElementsByClassName("elem").innerHTML);

As a result, if everything works correctly, we will get a pop-up window in which the text that is inside the div block will be displayed.

Please note that the result of executing the getElementsByClassName method will be an array of elements because There can be several elements with the same class on a page.

That is why at the end of the document.getElementsByClassName("elem") construction you need to indicate that the zero element of the array () is displayed. Counting in Javascript starts from zero, not one.

But the problem with using getElementsByClassName method is that this method is not supported in older versions of browsers.

There are some tricks to get around this, but it's redundant code. For example, you can use regular expressions:

If(document.getElementsByClassName == undefined) ( document.getElementsByClassName = function(cl) ( var retnode = ; var myclass = new RegExp("\\b"+cl+"\\b"); var elem = this.getElementsByTagName( "*"); for (var i = 0; i< elem.length; i++) { var classes = elem[i].className; if (myclass.test(classes)) { retnode.push(elem[i]); } } return retnode; } };

This is one way to solve the problem. But, to be honest, it’s not very acceptable for me to clutter up a page with unnecessary code, so most often I use the second option to solve the problem.

Option 2. Using the Jquery library.

Using the Jquery library makes it much easier to solve the problem of selecting elements by their class attribute. You need to use the following construction:

$(".elem")

Here elem is the class name assigned to the element.

You need to remember that in order for this to work, the Jquery library must first be included. It is added in the section, one of the ways this can be done is to add next line code:

In order for the library to be loaded there must be an Internet connection.

Let's see how this works with an example.

Block contents. alert($(".elem").html());

The script itself, as in the previous example, should be located below the code of the element with which you want to interact.

So here are two ways you can interact with elements that have the class attribute set. Choose the one that suits you best and put it into practice.

In order for the script to work with any page element, this element must first be found. There are several ways to do this in JavaScript. The found element is usually assigned to a variable, and subsequently, through this variable, script accesses the element and performs some actions with it.

Search by id

If an element is given an id attribute in the page code, then the element can be found by id. This is the easiest way. The element is searched using the getElementById() method of the global document object.

document.getElementById(id)

Options:

id - id of the element to be found. id is a string, so it must be in quotes.

Let's create a page, add an element to it and give it an id , and find this element in the script:

HTML code:

JavaScript:

var block = document.getElementById("block"); console.log(block);

We assigned the found element to the block variable and output the variable to the console. Open your browser console, the element should be listed there.

Since searching by id is the simplest and most convenient way, it is often used. If some element needs to be worked with in a script, then the id attribute is set to this element in the page code, even if it has not been set previously. And they find the element by id.

Search by class

The getElementsByClassName() method allows you to find all elements belonging to a particular class.

document.getElementsByClassName(class)

Options:

class - class of elements to be found

The method returns a pseudo-array containing the found elements. It is called a pseudo-array because many array methods do not work for it. But the main property remains - you can access any element of the array. Even if only one element is found, it is still in the array.

Let's add elements to the page and give them a class. We will place some of the elements inside the block that we created earlier. We will create the other part outside the block. The meaning of this will become clear a little later. Now the page will look like this:

HTML code:

JavaScript:

Now only those elements that are located in the block are found.

Search by tag

The getElementsByTagName() method finds all elements with a specific tag. It also returns a pseudo-array with the elements found.

document.getElementsByTagName(tag)

Options:

tag - element tag that need to be found

Let's find all p tags that are on the page:

var p = document.getElementsByTagName("p"); console.log(p);

This method can also be applied not to the entire document, but to a specific element. Find all p tags in the block.

Search by selector

There are querySelector() and querySelectorAll() methods that find elements that match a specific selector. That is, elements will be found to which the style would be applied if it were specified to such a selector. At the same time, the presence of such a selector in the page style is not at all necessary. These methods have nothing to do with CSS. The querySelectorAll() method finds all elements matching the selector. And the querySelector() method finds one element, which is the first in the page code. These methods can replace all the methods of searching for elements discussed earlier, because there is a selector by id, a selector by tag and many others.

document.querySelector(selector)

document.querySelectorAll(selector)

Selectors are written exactly the same as in CSS, just don't forget to put quotes.

Let's add a list to the page and find it using the selector. We are looking for only one element and we know for sure that it will be the first one, because there is only one on the page. Therefore, in this case it is more convenient to use the querySelector() method. But when using this method, you need to take into account that the same elements can be added to the page in the future. However, this applies to most methods.

HTML code:

These methods can also search for elements not in the entire document, but within a specific element.

In the example, we used only tag selectors. Try finding page elements using other selectors.

Adjacent Elements

You can find neighbors for the found element. Every element is an object, and neighboring elements can be obtained through the properties of this object. The previousElementSibling property contains the previous element, and the nextElementSibling property contains the next element.

element.previousElementSibling

element.nextElementSibling

Let's find the element following the block:

Child elements

The children property contains an array of children.

element.children

Let's find the child elements of the block.

The DOM standard provides several means of finding an element. These methods are getElementById, getElementsByTagName and getElementsByName.

JavaScript libraries offer more powerful search methods.

Search by id

The most convenient way to find an element in the DOM is to get it by id. To do this, use the call document.getElementById(id)

For example, the following code will change the text color to blue in the div "e c id="dataKeeper" :

Document.getElementById("dataKeeper").style.color = "blue"

Search by tag

The next way is to get all the elements with a certain tag, and look for the one you need among them. Document.getElementsByTagName(tag) is used for this. It returns an array of elements that have that tag.

For example, you can get the second element (numbering in the array starts from zero) with the li tag:

Document.getElementsByTagName("LI")

Interestingly, getElementsByTagName can be called not only for document , but generally for any element that has a tag (not text).

In this case, only those objects that are located under this element will be found.

For example, the following call gets the list of LI elements that are inside the first div tag:

Document.getElementsByTagName("DIV").getElementsByTagName("LI")

Get all children

Calling elem.getElementsByTagName("*") will return a list of all children of node elem in the order they are walked.

For example, on this DOM:

This code:

Var div = document.getElementById("d1") var elems = div.getElementsByTagName("*") for(var i=0; i

tell friends