How to grab the h3 text within a div - javascript

My website HTML has the following:
To grab the H3 text (SOME TEXT) as a variable in Tag Manager - when a user clicks on the div class "c-card c-card--primary c-parkcard " I think I need to use a DOM Element variable
But it's not returning the text.
Should the Element Selector be:
.c-card.c-card--primary.c-card__body.u-h6.c-card__title
However, it returns a null value in Tag Manager

The solution was to create a custom JS variable that when the image was clicked on would find the "c-card c-card--primary c-parkcard " div (9 parents up) and then go back down to find the h3 element by class and then return the text:
function(){
var z = {{Click Element}}.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode
.getElementsByClassName('u-h6 c-card__title')[0].innerText;
return z;
}

use of getElementsByClass is as simple as:
$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($html);
$content_node=$dom->getElementByClass("c-card__body");
$div_a_class_nodes=getElementsByClass($content_node, 'h3', 'u-h6 c-card__title');

You have set "h3" as "attribute name. "h3" is not an attribute (but the name of the tag). You do not want to set an attribute name at all, because you do not want to return the value of an attribute, but the innerText of the tag, and that is the default behaviour anyway.
If you use a DOM variable this will return the first instance on the page. If your selector matches several DOM nodes, you will still just get the first one, regardless if what the user clicks. If you expect this to update depending on the clicked element, you should rather use the {{Click Text}} variable (a built-in variable that you might have to enable first).
Chances are that the actual click element is not the h3, but the nested link inside, but that does not really change things for you (as in both cases the innerText will be the contained texted nodes, which in this case is the same).

Related

How do you add an element to a class (through JavaScript)?

Suppose that I want to add a newly created paragraph (using document.createElement("p")) into an existing div (with class name "container") in one of my html files. Is there a way to do this by calling some methods?
Since there's a getElementById() method, I figured I would use a getElementByClassName() method too, but that doesn't exist; what exists is getElementsByClassName() instead. One way I can get around this is to just change my div to have an id rather than a class name, and use the getElementById() to add the paragraph into the div, but I wanted to know if there was some method that I could call that would help me retrieve a class element (rather than the elements within the class itself).
I've tried looking for this online, but what I've found are answers to "how to add class names to elements" instead, which is not what I want to know.
For one element, this will chose first in DOM order:
var p = document.createElement("p");
p.innerHTML = "p element";
document.querySelector(".container").appendChild(p);
<div class="container">container</div>
For all elements with chosen class:
[...document.querySelectorAll('.container')].forEach(el => {
var p = document.createElement("p");
p.innerHTML = "p element";
el.appendChild(p);
})
<div class="container">container</div>
<div class="container">container2</div>
HTML DOM elements' IDs have to be unique within a document - and so asking for an element by Id will return you just one element (or null if there isn't a matching element).
However a class name can be applied to multiple elements, so you would expect to get zero one or more elements when searching by class, hence the getElementsByClassName returns a collection.
So if you have a list of elements with the class name container, and you know your document (hopefully) only contains one element with that name, you can pick the first element returned by the getElementsByClassName - e.g. getElementsByClassName('container')[0]
Note - getElementsByClassName returns all elements to which the class has been directly applied, for the children of the element on which it is being called. I've interpreted your query as relating to the whole document in the context of your original question.

What is the difference between textContent and a new text Node? [duplicate]

What's the advantage of creating a TextNode and appending it to an HTML element over setting directly its textContent?
Let's say I have a span.
var span = document.getElementById('my-span');
And I want to change its text. What's the advantage of using :
var my_text = document.createTextNode('Hello!');
span.appendChild(my_text);
over
span.textContent = 'hello';
It 's not really matter of advantage but of proper usage depending on the need.
The fundamental difference is that:
createTextNode() is a method and works just as its name says: it creates an element... then you must do something with it (like in your example, where you append it as a child);
so it is useful if you want to have a new element and place it somewhere
textContent is a property you may get or set, with a unique statement and nothing else;
so it is useful when you only want to change the content of an already existing element
Now in the precise case of your question, you said you want to change the text of the element...
To be more clear say you have the following HTML element:
<span>Original text</span>
If you're using your first solution:
var my_text = document.createTextNode('Hello!');
span.appendChild(my_text);
then it will end with:
<span>Original textHello!</span>
because you appended your textNode.
So you should use the second solution.

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!

How to find any text within a value of an attribute of a tag using jquery

hi is there any way i can find specific text within a value of an atrribute of an HTML tag, To be more specific, im trying to find out if the tag has "selected" within its "src" attribute e.g in this case i need to find out if selected exists, I can go in other routes to do this but i need this as a condition.
I am selecting the src of the img tag and adding this special text, but i dont want it to keep on adding e.g in this case its defeating the purpose of what im trying to do. I need to know if Selected has been inserted then ignore the particular image.
$(this).hover(function(){
var currentName = $(this).attr("src");
var theNumToSub = currentName.length - 4;
$(this).attr("src",$(this).attr("src").substr(0,theNumToSub)+"selected.jpg");
});
here is my code above for adding "Selected" in the first instance.
You can try with:
$(this).filter('[src$="selected.jpg"]');
it returns the same element if src ends with selected.jpg.
You can also filter if anywhere in src is selected keyword with:
$(this).filter('[src*="selected"]');
You can use the jQuery attribute contains selector :
$("img[src*='selected']");
You can use indexOf()
if($(this).attr("src").indexOf('selected')>0){
//selected is there in src
//your stuff here
}

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