panxpiotr
panxpiotr

Reputation: 56

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 managed to create a simple loop that finds every desired attribute of DOM element and creates array from it. 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.

var getAll = document.getElementsByTagName('*');
var myArray = [];

for (var i=0; i<getAll.length; i++) {
  getHref = getAll[i].getAttribute('href');
  if (getHref !== null) {
    myArray.push(getHref);
  }
}

I have no clue how to link my attributes with DOM elements. I've tried to use indexOf('') to find part of text but it doesn't work since it looks for full strings in array. Would anybody be so nice and help me out? I don't want to use any frameworks.

Upvotes: 2

Views: 935

Answers (2)

CodeSmith
CodeSmith

Reputation: 3197

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

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

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 );
});

Upvotes: 2

Related Questions