Going to specific instance of element class - javascript

I can use the following to create a indexed list of each instance of a particular item in a class.
var x = document.getElementsByClassName("page");
I can use the following to direct users to a particular id:
function CalledBySelectBox(value)
{
document.getElementById(value).scrollIntoView();
}
However, the elements I want to direct users to are not uniquely identified with Id's. How do I modify the second snippet above, to direct users to a particular instance/occurrence of x in the first snippet. Or to put it differently, how do I direct them to a particular instance of the class.
If its helpful, here is some sample html:
Some text of unknown length full of random tags and what have you.<span class="page">104</span> A bunch more text but we don't know how much and full of other tags.<span class="page">105</span> Some text of unknown length full of random tags and what have you <span class="page">106</span>

I think you are looking for something like this:
function ScrollToPage( page_num )
{
document.getElementsByClassName( 'page' )[ page_num ].scrollIntoView();
}

What getElementsByClassName(className) gives you is an array of elements, what document.getElementById(id) gives you is a single element. To scroll to an indexed element in the array you get, just call scrollIntoView() on that element.
var x = document.getElementsByClassName("page");
x[5].scrollIntoView();

Related

How do I display a unique id value with GTM?

I have multiple elements on a page with the same class name, but each element has a unique id name.
Example:
<div class="video-image" id="get-googled">
<div class="video-image" id="email-marketing">
I want to display the id value, but right now I am only able to have GTM return and display the first element on the page. I read this post: "Getting value of ID from class" and it didn't help and even explains doing it the simple way will only display the first elements value.
Do I need custom Javascript to create this properly?
If you want to get a specific div and you know where it is on the page you might be able to use a DOM variable with an nth of type query selector. But this seems cumbersome, and since it seems you want a list in any case I think you are better of with a custom javascript variable:
function() {
return document.querySelectorAll(".video-image");
}
which return a collection of DOM elements (you might want to check if there are actually elements with that class first).
The initial answer is the right start - this completes the loop:
<script>
var inputs = document.querySelectorAll(".video-image");
for (var i = 0; i < inputs.length; i++) {
alert(inputs[i].id);
}
</script>
Here is a JSFiddle to try it out - [https://jsfiddle.net/JMurphy22/kduybmsp/2/][1]

Split Javascript String into an array of strings by looking for keyword

Working on a personal project that parses through an HTML document inserted into a textarea and produces a new HTML document with added modifications.
What my issue is, I want split certain divs with class="dog" into an array with each element in the array being divs of class of dog.
HTML:
<div class="dog">
<div class="mouth"></div>
<dig class="legs"></dig>
</div>
<div class="dog">
<div class="mouth"></div>
<dig class="legs"></dig>
</div>
JS Idea:
dogs[x] = intext.slice(intext.indexOf('<div class="dog"'), /*next instance of dog*/);
Array would look like:
dog[0] = <div class="dog">
<div class="mouth"></div>
<dig class="legs"></dig>
</div>
I tried using .indexOf('<div class="dog"') to try and create an array of indexes so I can use it to split the main string but no luck.
Any ideas of how I can accomplish this?
There exists a feature called query selectors. With these you can select all elements with a certain class, or all elements of a certain tag, ...
This will suit your specific need: querySelectorAll
the regular querySelector() will only select the first element which is why you need to use querySelectorAll(). It will give you a list of elements with which you can continue working.
Example:
var dogDivs = document.querySelectorAll(".dog");
EDIT:
As you have just now mentioned it is text from a textarea, as suggested by an other answer you could first load it into your DOM structure. Preferrably in a hidden element so that the user is unaware of it.
First you need to load the content onto the DOM:
document.createElement("div").innerHtml(intext);
Then you can find the dog elements as the other answers have suggested:
var elements = document.getElementsByClassName('dog');
Be careful when loading user inputted data into the DOM, this can open doors to being hacked.
You should never parse html as a string. Use a DOMParser to convert it to a document and then you can use all the standard methods
var parser = new DOMParser();
var doc = parser.parseFromString(stringContainingHTMLSource, "Text Area Content");
divs = doc.getElementsBYTagName("div");
Then you can use the built in Document interface. For your specific case, here are a few methods you can use.
get an array of all divs:
document.getElementsByTagName("div");
get an array of all divs with a specific class:
document.getElementsByClassName("dog");
get an array of all divs with a specific id:
document.getElementById("id");
The full list of very useful methods can be found on MDN.
var elements = document.getElementsByClassName('dog');
var arr = [].slice.call(elements);
arr is the array you want to have. elements is HTMLCollection, and doesn't have array prototype methods.
You can try getting all elements with class dog:
var dogs = document.getElementsByClassName("dog");
But this will return all elements with class dog. Then you can try this snippet:
function splitByClass(tag, cl) {
var els = document.getElementsByClassName(cl);
var res = [];
for (i = 0; i < els.length; i++) {
if (els[i].tagName.toLowerCase() == tag.toLowerCase()) {
res.push(els[i]);
}
}
return res;
}
console.log(splitByClass("div","dog"));
If you want to parse it as text without converting it into a DOM object which could potentially error if there is any mistakes with the users input formatting. Try a solution like the one I suggested here for searching XML code:
https://stackoverflow.com/a/34299948/1011603
This will let you search for a start tag, eg and an end tag, you just need to tweak the .substring sizing for the size of your search start/end tag eg the div.
For the thing you are doing you don't use the slice tool. This would be used for a String and you don't use the index of because that's just searching a string for a specific part.
What you do want to use is the
document.querySelectorAll(".example");
You will put the class dog where the .example is as the same format.
This command will return an array of all of the possible divs
If you need any more help, go to this link
http://www.w3schools.com/jsref/met_document_queryselectorall.asp

javascript elements/tags array DOM node access

what's the different between using:
// assuming using elements/tags 'span' creates an array and want to access its first node
1) var arrayAccess = document.getElementsByTagName('elementName')[0]; // also tried property items()
vs
// assuming I assign an id value to the first span element/tag
// specifically calling a node by using it's id value
2) var idAccess = document.getElementById('idValue');
then if I want to change the text node....when using example 1) it will not work, for example:
arrayAccess.firstChild.nodeValue = 'some text';
or
arrayAccess.innerText/innerHTML/textContent = 'some text';
If I "access" the node through its id value then it seems to work fine....
Why is it that when using array it does not work? I'm new to javascript and the book I'm reading does not provide an answer.
Both are working,
In your first case you need to pass the tag name instead of the element name. Then only it will work.
There might be a case that you trying to set input/form elements using innerHTML. At that moment you need to use .value instead of innerHTML.
InnerHTML should be used for div, span, td and similar elements.
So your html markup example:
<div class="test">test</div>
<div class="test">test1</div>
<span id="test">test2</span>
<button id="abc" onclick="renderEle();">Change Text</button>
Your JS code:
function renderEle() {
var arrayAccess = document.getElementsByTagName('div')[0];
arrayAccess.innerHTML = "changed Text";
var idEle = document.getElementById('test');
idEle.innerHTML = "changed this one as well";
}
Working Fiddle
When you use document.getElementsByTagName('p'), the browser traverses the rendered DOM tree and returns a node list (array) of all elements that have the matching tag.
When you use document.getElementById('something'), the browser traverses the rendered DOM tree and returns a single node matching the ID if it exists (since html ID's are unique).
There are many differences when to use which, but one main factor will be speed (getElementById is much faster since you're only searching for 1 item).
To address your other question, you already have specified that you want the first element in the returned nodeList (index [0]) in your function call:
var arrayAccess = document.getElementsByTagName('elementName')[0];
Therefore, arrayAccess is already set to the first element in the returned query. You should be able to access the text by the following. The same code should work if you used document.getElementById to get the DOM element:
console.log(arrayAccess.textContent);
Here's a fiddle with an example:
http://jsfiddle.net/qoe30w2w/
Hope this helps!

HTML Javascript | how to get a value of a links array

I have a small html code base that produces a list of unique links, I want to get each an every link's text value using java script (not the link only the text).
my sample code (doesn't work)
for (var x = 0; x < document.getElementById("folderLink").length; x++) {
alert(document.getElementById("folderLink")[x].innerHtml);
}
HTML
<a id="folderLink" href="somelink">Dynamic Text Text Text</a>
assume that this is a one link of the list.
Thanks.
getElementById will only ever return one element, regardless of how many there may be with that ID. Because there should only ever be one element of any ID.
So you can't access its length because it's not a collection it's a DOM node.
You could use getElementsByClassName

Parse string for text between divs

I have a string of html text stored in a variable:
var msg = '<div class="title">Alert</div><div class="message">New user just joined</div>'
I would like to know how I can filter out "New user just joined" from the above variable in jQuery/Javascript so that I can set the document title to just the message.
Like this:
document.title = $(msg).filter("div.message").text();
Note that if the message changes to be wrapped in an element, you'll need to replace filter with children.
EDIT: It looks like the div that you want is nested in other element(s).
If so, you can do it like this:
document.title = $("div.message", msg).text();
Explanation: $('<div>a</div><div>b</div>') creates a jQuery object holding two different <div> elements. You can find the one you're looking for by calling the filter function, which finds mathcing elements that are in the jQuery object that you call it on. (Not their children)
$('<p><div>a</div><div>b</div><p>') creates a jQuery object holding a single <p> element, and that <p> element contains two <div> elements as children. Calling $('selector', 'html') will find all descendants of the elements in the HTML that match the selector. (But it won't return the root element(s))
This is a hack and not very clean, but it should work:
add a div node and set its html to your text message,
get the text of the added element and store it in a variable
destroy the node
set the title with the contents of the variable in step 2

Categories

Resources