2

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.

2 Answers 2

2

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 );
});
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.