Hardware and software setup

Javascript and jquery element selection by class (class attribute). Web page search organization in JavaScript (without jQuery) Search by tag

A couple of days ago I received a test task from a company for a Front-end dev vacancy. Of course, the task consisted of several points. But now we will talk about only one of them - the organization of the search on the page. Those. banal search by the text entered in the field (similar to Ctrl + F in the browser). The peculiarity of the task was that the use of any JS frameworks or libraries is prohibited. Everything is written in native JavaScript.

Finding a turnkey solution

First thought: someone already wrote exactly this, you need to google and copy-paste. So I did. In an hour, I found two good scripts that essentially worked the same way, but were written differently. I chose the one whose code I understood better and put it on my page.

If anyone is interested, I took the code.

The script worked right away. I thought that the issue was resolved, but as it turned out, no offense to the author of the script, there was a huge flaw in it. The script searched the entire contents of the tag... and, as you might have guessed, searching for any combination of characters that resembled the tag or its attributes broke the entire HTML page.

Why did the script work incorrectly?

Everything is simple. The script works as follows. First, write the entire contents of the tag to the variable body, then look for matches with a regular expression (specified by the user when typing in a text field) and then replace all matches with the following code:

...found match...
And then we replace the current tag body to the new one received. The markup is updated, styles are changed, and all found results are highlighted in yellow on the screen.

You probably already understand what the problem is, but I'll explain in more detail anyway. Imagine entering the word in the search field "div". As you can see, inside body There are many other tags, including div. And if we all "div" apply the styles indicated above, then it will no longer be a block, but it is not clear what, since the structure breaks. As a result, after rewriting the markup, we will get a completely broken web page. It looks like this.

As you can see, the page is completely broken. In short, the script turned out to be non-working, and I decided to write my own from scratch, which is what this article is dedicated to.

So we write a script from scratch

How everything looks to me.

Now we are interested in a form with a search. I circled it with a red line.

Let's understand a little. I implemented it as follows (so far pure HTML). Form with three tags.

First- to enter text;
Second- for to cancel the search (deselect);
The third- for search (highlight found results).


So, we have an input field and 2 buttons. JavaScript will be written in the js.js file. Let's assume that you have already created and connected it.

The first thing we will do: we will write the function calls when the search button and the cancel button are clicked. It will look like this:


Let's explain a little what is needed here and why.

We give a field with text id="text-to-find" (by this id we will refer to the element from js).

We give the cancel button the following attributes: type="button" onclick="javascript: FindOnPage("text-to-find",false); return false;"

- Type: button
- When clicked, the FindOnPage("text-to-find",false); function is called. and passes the id of the field with text, false

We give the search button the following attributes: type="button" onclick="javascript: FindOnPage("text-to-find",true); return false;"

- Type: submit (not a button because here you can use Enter after entering in the field, but you can also use button)
- When clicked, the FindOnPage("text-to-find",true); function is called. and passes the id of the field with text, true

You probably noticed 1 more attribute: true/false . We will use it to determine which button was clicked (cancel the search or start the search). If we click on cancel, then we transfer false. If we click on search, then we pass true.

Before we start writing code, let's digress and first discuss how things should work. Those. Essentially write down a plan of action. So, we need to search the page when entering text in the field, but tags and attributes cannot be affected. Those. only text objects. How to achieve this - I'm sure there are many ways. But now we will use regular expressions.

So the next regular expression will only search for the text trail. of the form: ">... text...<". Т.е. будет проходить поиск только текстовых объектов, в то время, как теги и атрибуты будут оставаться нетронутыми.

/>(.*?)So we will find the necessary parts of the code that we will parse and look for matches with the text that the user entered. Then we will add styles to the found objects and then replace the html code with a new one.

Let's get started. First, the variables we need.

Var input,search,pr,result,result_arr, locale_HTML, result_store; //input - we accept the text entered by the user //search - we make a regular expression from the string //pr - we save the current one into it //result - fetching text from pr (i.e. cutting off tags and attributes) //result_arr - similar to pr, but with styles for highlighting //locale_HTML - original which we will not change, we use to reset the styles
And we will immediately determine locale_HTML meaning whether we are looking for something or not. This is necessary to immediately save the original page and be able to reset the styles.

Var input,search,pr,result,result_arr, locale_HTML, result_store; locale_HTML = document.body.innerHTML; // save the entire body into a variable (Source)
Ok, now it's time to create a function that is called from us from DOM. Let's immediately estimate that inside we should have 2 functions, each of which works depending on the button pressed. After all, we either conduct a search, or reset it. And it is controlled by the attribute true/false, as you remember. You also need to understand that when you search again, the old styles should be reset. Thus we get the following:

Var input,search,pr,result,result_arr, locale_HTML, result_store; locale_HTML = document.body.innerHTML; // save the entire body (Initial) into a variable function FindOnPage(name, status) ( if(status) ( FindOnPageBack(); FindOnPageGo(); ) // clear the past and highlight the found if(!status) ( FindOnPageBack(); ) //Remove selection)
Ok, part of the logic is implemented, moving on. It is necessary to check the received word for the number of characters. After all, why do we need to look for 1 letter / symbol. In general, I decided to limit this possibility to 3+ characters.

So, first we take the value that the user entered, and, depending on its length, we execute either the main search function, or the function of displaying a warning and zeroing. It will look like this:

<3&&status==true) { alert("Для поиска вы должны ввести три или более символов"); function FindOnPageBack() { document.body.innerHTML = locale_HTML; } //обнуляем стили } if(input.length>=3) ( //do a search ) function FindOnPageBack() ( document.body.innerHTML = locale_HTML; ) //set the styles to zero if(status) ( FindOnPageBack(); FindOnPageGo(); ) //clear the past and highlight the found if( !status) ( FindOnPageBack(); ) //Remove selection )
Let me explain this part of the code. The only thing that could not be clear is this line:

function FindOnPageBack() ( document.body.innerHTML = locale_HTML; )

Everything is simple here: the method innerHTML returns html object code. In this case, we simply replace the current body to the original one, which we saved when loading the entire page.

Var input,search,pr,result,result_arr, locale_HTML, result_store; locale_HTML = document.body.innerHTML; // save the entire body (Initial) into a variable function FindOnPage(name, status) ( input = document.getElementById(name).value; //get the value from the field in html if(input.length<3&&status==true) { alert("Для поиска вы должны ввести три или более символов"); function FindOnPageBack() { document.body.innerHTML = locale_HTML; } //обнуляем стили } if(input.length>=3) ( function FindOnPageGo() ( search = "/"+input+"/g"; //make a regular expression out of the string pr = document.body.innerHTML; //save the entire body to a variable result = pr.match(/ >(.*?)So, at this stage, we already have the main variables and values. Now we need to give the necessary sections of the code styles with a selected background. Those. checking the selected text for a regular expression (in fact, we again parse the text selected by the regular expression with a regular expression). To do this, you need to make a regular expression from the entered text (done), and then execute the method passed as a tactic. Here the method will help us eval().

In general, after we replace the text and get the result with styles, we need the current html replace with the received one. We do.

Var input,search,pr,result,result_arr, locale_HTML, result_store; locale_HTML = document.body.innerHTML; // save the entire body (Initial) into a variable function FindOnPage(name, status) ( input = document.getElementById(name).value; //get the value from the field in html if(input.length<3&&status==true) { alert("Для поиска вы должны ввести три или более символов"); function FindOnPageBack() { document.body.innerHTML = locale_HTML; } //обнуляем стили } if(input.length>=3) ( function FindOnPageGo() ( search = "/"+input+"/g"; //make a regular expression out of the string pr = document.body.innerHTML; //save the entire body to a variable result = pr.match(/ >(.*?)"+input+""); // find the necessary elements, set the style and save to a new array ) for(var i=0; i In fact, everything is ready, and the script is already running. But let's add a couple more details for beauty.

1) Trim spaces from the text that the user enters. Paste this code:

Input = numer.replace(/^\s+/g,""); input = numer.replace(/(1,)/g," ");
After this line:

Input = document.getElementById(name).value; // get value from field in html
2) Let's check for matches (if no matches are found, let us know about it). We insert this code inside the function FindOnPageGo() after the variables.

That's it. Of course, you can add a scroll to the first result found, live ajax search, and in general you can improve it endlessly. Now this is a rather primitive search on the site. The purpose of the article was to help newbies if the same question arises as I have. After all, I did not find a simple ready-made solution.

P.S.: for correct operation, it is necessary to remove text wrapping in the html document in those places where there is plain text between tags.

For example, instead of

Blah blah blah


Necessary

Blah blah blah


This is not important, you can get rid of these transfers automatically on the service, but at the same time you can tell me how to fix it if you understand before me.

Also, if someone wrote something similar, but with a live search, share the source, it will be interesting to parse.

I would be glad to hear constructive criticism, opinions, maybe recommendations.

The other day I added a little code, did a live search on the page. So the question is removed. The code HTML didn't change. JS You can view .

The search is conducted by tags with the class "place_for_live_search". So in order for the algorithm to parse the desired content, add a class and you're done.

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

More powerful search methods are offered by javascript libraries.

Search by id

The most convenient way to find an element in the DOM is to get it by id . This is done by calling document.getElementById(id)

For example, the following code will change the color of the text 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 search among them for the one you need. For this, document.getElementsByTagName(tag) is used. 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 on document , but in general on any element that has a tag (not text).

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

For example, the following call gets a 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 the elem node in the order in which they.

For example, on this DOM:

Code like this:

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

Will output the sequence: ol1, li1, li2 .

Search by name: getElementsByName

The document.getElementsByName(name) method returns all elements whose name (name attribute) is equal to the given one.

It only works on elements for which the specification explicitly provides a name attribute: form , input , a , select , textarea , and a number of other rarer ones.

The document.getElementsByName method will not work on other elements like div , p , etc.

other methods

There are other ways to search the DOM: XPath, cssQuery, etc. As a rule, they are implemented by javascript libraries to extend the standard features of browsers.

There is also a getElementsByClassName method for finding elements by class, but it does not work at all in IE, so no one uses it in its pure form.

A common typo is due to the absence of a letter s in the name of the getElementById method, while other methods have this letter: getElement s ByName .

The rule here is simple: one element - Element , many - Element s. All *Element methods s* return a list of nodes.

Last update: 1.11.2015

To work with the DOM structure in JavaScript, the document object is defined in the global window object. The document object provides a number of properties and methods for manipulating page elements.

Search for elements

The following methods are used to search for elements on a page:

    getElementById(value) : selects the element whose id attribute is equal to value

    getElementsByTagName(value) : selects all elements whose tag is equal to value

    getElementsByClassName(value) : selects all elements that have class value

    querySelector(value) : selects the first element that matches the css selector value

    querySelectorAll(value) : selects all elements that match the css selector value

For example, let's find an element by id:

By calling document.getElementById("header") we find the element with id="header". And using the innerText property, you can get the text of the found element.

Search by specific tag:

header

First paragraph

Second paragraph

By calling document.getElementsByTagName("p") we find all paragraph elements. This call returns an array of found elements. Therefore, in order to get the individual elements of the array, it is necessary to run through them in a loop.

If we need to get only the first element, then we can access the first element of the found collection of objects:

VarpElement = document.getElementsByTagName("p"); document.write("Paragraph text: " + pElement.innerText);

Getting an element by class:

Article title

First paragraph

Second paragraph

Select by css selector:

Article abstract

First paragraph

Second paragraph

The document.querySelector(".annotation p") expression finds an element that matches the selector.annotation p . If there are several elements on the page that match the selector, then the method will select the first of them. As a result, the browser will display:

Article annotation First paragraph Second paragraph Selector text: Article annotation

To get all the elements in a selector, you can similarly use the document.querySelectorAll method, which returns an array of the found elements:

Article abstract

First paragraph

Second paragraph

Browser output:

Article annotation First paragraph Second paragraph Selector text 0: First paragraph Selector text 1: Second paragraph

A couple of days ago I received a test task from a company for a Front-end dev vacancy. Of course, the task consisted of several points. But now we will talk about only one of them - the organization of the search on the page. Those. banal search by the text entered in the field (similar to Ctrl + F in the browser). The peculiarity of the task was that the use of any JS frameworks or libraries is prohibited. Everything is written in native JavaScript.

Finding a turnkey solution

First thought: someone already wrote exactly this, you need to google and copy-paste. So I did. In an hour, I found two good scripts that essentially worked the same way, but were written differently. I chose the one whose code I understood better and put it on my page.

If anyone is interested, I took the code.

The script worked right away. I thought that the issue was resolved, but as it turned out, no offense to the author of the script, there was a huge flaw in it. The script searched the entire contents of the tag... and, as you might have guessed, searching for any combination of characters that resembled the tag or its attributes broke the entire HTML page.

Why did the script work incorrectly?

Everything is simple. The script works as follows. First, write the entire contents of the tag to the variable body, then look for matches with a regular expression (specified by the user when typing in a text field) and then replace all matches with the following code:

...found match...
And then we replace the current tag body to the new one received. The markup is updated, styles are changed, and all found results are highlighted in yellow on the screen.

You probably already understand what the problem is, but I'll explain in more detail anyway. Imagine entering the word in the search field "div". As you can see, inside body There are many other tags, including div. And if we all "div" apply the styles indicated above, then it will no longer be a block, but it is not clear what, since the structure breaks. As a result, after rewriting the markup, we will get a completely broken web page. It looks like this.

As you can see, the page is completely broken. In short, the script turned out to be non-working, and I decided to write my own from scratch, which is what this article is dedicated to.

So we write a script from scratch

How everything looks to me.

Now we are interested in a form with a search. I circled it with a red line.

Let's understand a little. I implemented it as follows (so far pure HTML). Form with three tags.

First- to enter text;
Second- for to cancel the search (deselect);
The third- for search (highlight found results).


So, we have an input field and 2 buttons. JavaScript will be written in the js.js file. Let's assume that you have already created and connected it.

The first thing we will do: we will write the function calls when the search button and the cancel button are clicked. It will look like this:


Let's explain a little what is needed here and why.

We give a field with text id="text-to-find" (by this id we will refer to the element from js).

We give the cancel button the following attributes: type="button" onclick="javascript: FindOnPage("text-to-find",false); return false;"

- Type: button
- When clicked, the FindOnPage("text-to-find",false); function is called. and passes the id of the field with text, false

We give the search button the following attributes: type="button" onclick="javascript: FindOnPage("text-to-find",true); return false;"

- Type: submit (not a button because here you can use Enter after entering in the field, but you can also use button)
- When clicked, the FindOnPage("text-to-find",true); function is called. and passes the id of the field with text, true

You probably noticed 1 more attribute: true/false . We will use it to determine which button was clicked (cancel the search or start the search). If we click on cancel, then we transfer false. If we click on search, then we pass true.

Before we start writing code, let's digress and first discuss how things should work. Those. Essentially write down a plan of action. So, we need to search the page when entering text in the field, but tags and attributes cannot be affected. Those. only text objects. How to achieve this - I'm sure there are many ways. But now we will use regular expressions.

So the following regex will only look for the text trail. of the form: ">... text...<". Т.е. будет проходить поиск только текстовых объектов, в то время, как теги и атрибуты будут оставаться нетронутыми.

/>(.*?)So we will find the necessary parts of the code that we will parse and look for matches with the text that the user entered. Then we will add styles to the found objects and then replace the html code with a new one.

Let's get started. First, the variables we need.

Var input,search,pr,result,result_arr, locale_HTML, result_store; //input - we accept the text entered by the user //search - we make a regular expression from the string //pr - we save the current one into it //result - fetching text from pr (i.e. cutting off tags and attributes) //result_arr - similar to pr, but with styles for highlighting //locale_HTML - original which we will not change, we use to reset the styles
And we will immediately determine locale_HTML meaning whether we are looking for something or not. This is necessary to immediately save the original page and be able to reset the styles.

Var input,search,pr,result,result_arr, locale_HTML, result_store; locale_HTML = document.body.innerHTML; // save the entire body into a variable (Source)
Ok, now it's time to create a function that is called from us from DOM. Let's immediately estimate that inside we should have 2 functions, each of which works depending on the button pressed. After all, we either conduct a search, or reset it. And it is controlled by the attribute true/false, as you remember. You also need to understand that when you search again, the old styles should be reset. Thus we get the following:

Var input,search,pr,result,result_arr, locale_HTML, result_store; locale_HTML = document.body.innerHTML; // save the entire body (Initial) into a variable function FindOnPage(name, status) ( if(status) ( FindOnPageBack(); FindOnPageGo(); ) // clear the past and highlight the found if(!status) ( FindOnPageBack(); ) //Remove selection)
Ok, part of the logic is implemented, moving on. It is necessary to check the received word for the number of characters. After all, why do we need to look for 1 letter / symbol. In general, I decided to limit this possibility to 3+ characters.

So, first we take the value that the user entered, and, depending on its length, we execute either the main search function, or the function of displaying a warning and zeroing. It will look like this:

<3&&status==true) { alert("Для поиска вы должны ввести три или более символов"); function FindOnPageBack() { document.body.innerHTML = locale_HTML; } //обнуляем стили } if(input.length>=3) ( //do a search ) function FindOnPageBack() ( document.body.innerHTML = locale_HTML; ) //set the styles to zero if(status) ( FindOnPageBack(); FindOnPageGo(); ) //clear the past and highlight the found if( !status) ( FindOnPageBack(); ) //Remove selection )
Let me explain this part of the code. The only thing that could not be clear is this line:

function FindOnPageBack() ( document.body.innerHTML = locale_HTML; )

Everything is simple here: the method innerHTML returns html object code. In this case, we simply replace the current body to the original one, which we saved when loading the entire page.

Var input,search,pr,result,result_arr, locale_HTML, result_store; locale_HTML = document.body.innerHTML; // save the entire body (Initial) into a variable function FindOnPage(name, status) ( input = document.getElementById(name).value; //get the value from the field in html if(input.length<3&&status==true) { alert("Для поиска вы должны ввести три или более символов"); function FindOnPageBack() { document.body.innerHTML = locale_HTML; } //обнуляем стили } if(input.length>=3) ( function FindOnPageGo() ( search = "/"+input+"/g"; //make a regular expression out of the string pr = document.body.innerHTML; //save the entire body to a variable result = pr.match(/ >(.*?)So, at this stage, we already have the main variables and values. Now we need to give the necessary sections of the code styles with a selected background. Those. checking the selected text for a regular expression (in fact, we again parse the text selected by the regular expression with a regular expression). To do this, you need to make a regular expression from the entered text (done), and then execute the method passed as a tactic. Here the method will help us eval().

In general, after we replace the text and get the result with styles, we need the current html replace with the received one. We do.

Var input,search,pr,result,result_arr, locale_HTML, result_store; locale_HTML = document.body.innerHTML; // save the entire body (Initial) into a variable function FindOnPage(name, status) ( input = document.getElementById(name).value; //get the value from the field in html if(input.length<3&&status==true) { alert("Для поиска вы должны ввести три или более символов"); function FindOnPageBack() { document.body.innerHTML = locale_HTML; } //обнуляем стили } if(input.length>=3) ( function FindOnPageGo() ( search = "/"+input+"/g"; //make a regular expression out of the string pr = document.body.innerHTML; //save the entire body to a variable result = pr.match(/ >(.*?)"+input+""); // find the necessary elements, set the style and save to a new array ) for(var i=0; i In fact, everything is ready, and the script is already running. But let's add a couple more details for beauty.

1) Trim spaces from the text that the user enters. Paste this code:

Input = numer.replace(/^\s+/g,""); input = numer.replace(/(1,)/g," ");
After this line:

Input = document.getElementById(name).value; // get value from field in html
2) Let's check for matches (if no matches are found, let us know about it). We insert this code inside the function FindOnPageGo() after the variables.

That's it. Of course, you can add a scroll to the first result found, live ajax search, and in general you can improve it endlessly. Now this is a rather primitive search on the site. The purpose of the article was to help newbies if the same question arises as I have. After all, I did not find a simple ready-made solution.

P.S.: for correct operation, it is necessary to remove text wrapping in the html document in those places where there is plain text between tags.

For example, instead of

Blah blah blah


Necessary

Blah blah blah


This is not important, you can get rid of these transfers automatically on the service, but at the same time you can tell me how to fix it if you understand before me.

Also, if someone wrote something similar, but with a live search, share the source, it will be interesting to parse.

I would be glad to hear constructive criticism, opinions, maybe recommendations.

The other day I added a little code, did a live search on the page. So the question is removed. The code HTML didn't change. JS You can view .

The search is conducted by tags with the class "place_for_live_search". So in order for the algorithm to parse the desired content, add a class and you're done.

In order for the script to work with some element of the page, 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 later, through this variable, the script accesses the element and performs some actions with it.

Search by id

If the 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 document global object.

document.getElementById(id)

Parameters:

id - the 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 displayed the variable in the console. Open the browser console, it should contain the element.

Since search by id is the easiest and most convenient way, it is often used. If you need to work with some element in a script, then the id attribute is set for this element in the page code, even if it has not been set before. And 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)

Parameters:

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 refer to 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. Some of the elements will be placed inside the block that we created earlier. The other part will be created 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 found elements.

document.getElementsByTagName (tag)

Parameters:

tag - tag of elements to be found

Let's find all the 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 given selector. That is, elements will be found to which the style would have been applied if it had been specified to such a selector. At the same time, the presence of such a selector in the page style is not necessary at all. These methods have nothing to do with CSS. The querySelectorAll() method finds all elements that match the selector. And the querySelector() method finds one element, which is the first element in the page code. These methods can replace all the ways to find elements discussed earlier, because there is an id selector, a tag selector, and many others.

document.querySelector(selector)

document.querySelectorAll(selector)

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

Let's add a list to the page and find it by the selector. We are looking for only one element and we know for sure that it will be the first one, because it is the 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 single element.

In the example, we used only selectors by tag. Try to find page elements using other selectors.

Adjacent elements

For the found element, you can find neighbors. Each 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

Find the element following the block:

Child elements

The children property contains an array of children.

element.children

Find the child elements of the block.

Liked the article? Share with friends!
Was this article helpful?
Yes
Not
Thanks for your feedback!
Something went wrong and your vote was not counted.
Thanks. Your message has been sent
Did you find an error in the text?
Select it, click Ctrl+Enter and we'll fix it!