Skip to content Skip to sidebar Skip to footer

Finding Dom Element With Part Of Attribute With Vanilla Javascript

Let's say that I have a website and I want to use script that loops trough its DOM elements and points out these elements that attribute contains part of specified text. I've manag

Solution 1:

Now I want to pair my array attribute value with DOM element that it belongs to and also be able to find out specified part of text that matches the array element (attribute) and DOM element.

Why not simply get only those elements that matches using the contains selector

var getAll = document.querySelectorAll("[href*='text-to-be-matched']");

This is a NodeList which you can iterate with for-loop and index the DOM elements with what you have found.

var attributeValToDOMMap = {};
getAll.forEach( function( element ){
   var hrefVal = element.getAttribute( "href" );
   attributeValToDOMMap[ hrefVal ] =  attributeValToDOMMap[ hrefVal ] || []; //in case one href value is common with multiple DOM elements
   attributeValToDOMMap[ hrefVal ].push( element );
});

Solution 2:

You wanna filter a href attribute by some text?

You can use .indexOf(), I don't see a reason why not.

Or you can improve your selector at the start (but that has already been suggested).

Here is the fiddle showing 1 line of code added to yours in order to filter upon some substring appearing in href.

fiddle

Post a Comment for "Finding Dom Element With Part Of Attribute With Vanilla Javascript"