How to find data from html and store it using jQuery - javascript

My HTML
<div class="product">
<img src="#">
<div class="priceStore">
<p data="40">Item 1</p>
</div>
</div>
How, using jQuery would I retrieve the data and store it?
My attempt:
$('.product').mousedown(function(event) {
var x = $('.priceStore').parent().find(data);
console.log(x);
});
Thanks!

There are a few different ways to write the selector but to get the value of an attribute you can use .attr()
Something like this works for this case
$('.product').mousedown(function(event) {
var x = $('.priceStore p').attr('data');
console.log(x);
});

Personally I would rewrite your HTML as follows:
<div class="product">
<img src="#">
<div class="priceStore">
<p id="data" data="40">Item 1</p>
</div>
</div>
And then access the data element like this within your Javascript:
document.getElementById("data").getAttribute('data');
Advantages:
- You don't need jQuery for this, it's basic javascript.
- You can apply an identifier to multiple elements and access/manipulate data
- Adding a second or third P tag won't break your code.
Ergo if you wanted to do so...
<div class="product">
<img src="#">
<div class="priceStore">
<p id="apple" data="40">Item 1</p>
<p id="orange" data="50">Item 2</p>
<p id="grape" data="80">Item 3</p>
</div>
</div>
You could then:
document.getElementById("apple").getAttribute('data');
document.getElementById("orange").getAttribute('data');
document.getElementById("grape").getAttribute('data');

Related

TypeError: Cannot read properties of null (reading 'addEventListener') javascript

I am trying to add a button but it is showing me this error.
here is my html code
<div card-container>
<template class="mainTemplate">
<div class="cards">
<div class="card">
<img data-image src="" alt="">
<div data-title class="header"></div>
<div data-body class="body"></div>
<button data-button class="btn">read more</button>
<p data-paragraph class="fullText"></p>
</div>
</div>
</template>
</div>
here is the javascript code
let showDitail = document.querySelector(".btn");
showDitail.addEventListener("click", showMore);
function showMore(){
alert("e")
}
You're using the <template> tag, which is an element that holds html markup but it's not rendered on page load.
In order to render its contents, one has to handle the <template> element via javascript, using the html structure as - in fact - a template for filling another structure (a table, a divs grid, etc.).
Since the sub-elements of <template> are not part of the DOM yet, let showDitail = document.querySelector(".btn"); will result in null. That's why you cannot bind events to it.
Either change the tag to something else (a div maybe), or handle the template properly via javascript.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template
let showDitail = document.querySelector(".btn");
showDitail.addEventListener("click", showMore);
function showMore(){
alert("e")
}
<div card-container>
<div class="mainTemplate">
<div class="cards">
<div class="card">
<img data-image src="" alt="">
<div data-title class="header"></div>
<div data-body class="body"></div>
<button data-button class="btn">read more</button>
<p data-paragraph class="fullText"></p>
</div>
</div>
</div>
</div>

add data- attributes by reading values from DOM

I have the below html structure and I'm trying to get the text of h tags and add as a data- attribute in the corresponding tags:
<div class="content">
<div class="body">
<h1>foo</h1>
<p>para-test1</p>
<p>para-test2</p>
<div class="link">
anchor1
anchor2
anchor3
</div>
</div>
</div>
<div class="content">
<div class="body">
<h1>bar</h1>
<p>para-test3</p>
<div class="link">
anchor4
</div>
</div>
</div>
So 'foo' should be set as a data attribute value for anchor 1,2,3 elements and
'bar' should be set as a data attribute value for anchor 4. Something like this:
<a data-custom="foo" href="#">anchor1</a>
<a data-custom="foo" href="#"">anchor2</a>
<a data-custom="foo" href="#">anchor3</a>
<a data-custom="bar" href="#">anchor4</a>
I tried to iterate over the elements and I'm struck at the second loop.
$(".content .body").each(function() {
$(this).find(".link").attr("data-hN", $(this).next(":header").text());
});
You have an extra double quote two times in your HTML. But, fixing that and foregoing JQuery (which is overkill for such a trivial task), see comments inline below:
// Loop over the links
document.querySelectorAll("div.link > a").forEach(function(item){
// Set the current link data-custom attribute to the nearest
// .body ancestor and the first heading element within that text
item.dataset.custom = item.closest(".body").querySelector(":first-child").textContent;
console.log(item);
});
<div class="content">
<div class="body">
<h1>foo</h1>
<p>para-test1</p>
<p>para-test2</p>
<div class="link">
anchor1
anchor2
anchor3
</div>
</div>
</div>
<div class="content">
<div class="body">
<h1>bar</h1>
<p>para-test3</p>
<div class="link">
anchor4
</div>
</div>
</div>

Get an element with specific parent

I want to get an element that it's parent has a specific id in javascript. For example if we have an html code like this
<div id="1">
<p name="para"> first div </p>
<a> </a>
</div>
<div id="2">
<p name="para"> second div </p>
<a> </a>
</div>
<div id="3">
<p name="para"> third div </p>
<a> </a>
</div>
I tried this but it did not work.
document.getElementById('1').getElementByName("para").innerHTML = "";
Use a queryselector:
document.querySelector('#1 > [name=para]').innerHTML = "";
Side note: Id's shouldn't start with a number. This could cause issues.
Note: Using characters except ASCII letters, digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.
A simple way to fix the id problem would be to prefix the id with something that isn't a number such as an underscore (You will also need to change the html to use an underscore as well):
document.querySelector('#_1 > [name=para]').innerHTML = "";
document.getElementById("2").childNodes[1].innerHTML;
You can use querySelector, but with a unicode as ids shouldn't start with numbers.
document.querySelector('#\\33 > p[name="para"]').innerHTML = 'Foo';
document.querySelector('#\\33 > p[name="para"]').innerHTML = 'Foo';
<div id="1">
<p name="para"> first div </p>
<a> </a>
</div>
<div id="2">
<p name="para"> second div </p>
<a> </a>
</div>
<div id="3">
<p name="para"> third div </p>
<a> </a>
</div>
Just another way to do it. Note that using querySelector is preferred way of doing it as the other answers showed.
const el = document.getElementById('1').childNodes;
const para = [...el]
.filter(item => item.nodeType === document.ELEMENT_NODE)
.filter(item => item.tagName === 'P');
console.log(para[0]);
<div id="1">
<p name="para"> first div </p>
<a> </a>
</div>
<div id="2">
<p name="para"> second div </p>
<a> </a>
</div>
<div id="3">
<p name="para"> third div </p>
<a> </a>
</div>

Get the value of a tag with javascript

I would like to get the value of a tag after clicking on it. I just use javascript and no jquery.
Here's my html :
<div class="touche 1">
<h1>1</h1>
</div>
<div class="touche 2">
<h1>2</h1>
</div>
<div class="touche 3">
<h1>3</h1>
</div>
I need the values 1,2,3, etc... into a variable. The div's work like a calculator button !
Thanks !
Here is the code
function getval(thisa)
{
alert(thisa.innerHTML);
}
<div class="touche 1">
<h1 onclick="getval(this)">1</h1>
</div>
<div class="touche 2">
<h1 onclick="getval(this)">2</h1>
</div>
<div class="touche 3">
<h1 onclick="getval(this)">3</h1>
</div>
Use following js to do this. JSFIDDLE
var controls = document.getElementsByClassName("touche");
for(var i = 0;i<controls.length;i++)
{
controls[i].onclick = function() {
console.log(this.childNodes[1].innerText);
alert(this.childNodes[1].innerText);
};
}
If you want to directly access the <h1> tags, you can use getElementsByTagName(), which returns a collection of HTMLElements. You can iterate over them an attach a click event handler.
Inside the event handler, you can use it's textContent property for getting the text (read as value) as follows:
var elms = document.getElementsByTagName("h1");
for(var i=0;i<elms.length;i++){
elms[i].addEventListener("click",function(){
console.log(this.textContent);
});
}
<div class="touche 1">
<h1>1</h1>
</div>
<div class="touche 2">
<h1>2</h1>
</div>
<div class="touche 3">
<h1>3</h1>
</div>
If you want to bind the listener for the <div>'s, You can use getElementsByTagName() or getElementsByClassName() for accessing the elements, loop through them and attach click event listener.
Inside the event handler, you can use the children property to access the <h1> get it's value as mentioned above.
var elms = document.getElementsByClassName("touche");
for(var i=0;i<elms.length;i++){
elms[i].addEventListener("click",function(){
console.log(this.children[0].textContent);
});
}
<div class="touche 1">
<h1>1</h1>
</div>
<div class="touche 2">
<h1>2</h1>
</div>
<div class="touche 3">
<h1>3</h1>
</div>

Help with hiding DIV tags, based on text content, using Greasemonkey

I am looking for a way to write a Greasemonkey script which will take the following snippet of code and only show the code blocks consisting of <div class="A" where both "passtest" and "State1" are present.
<div class="A">
<div class="B">
<a href="/link1">
<img class="imgClass" src="http://link.com/img.img" title="imgTitle"/>
</a>
</div>
<div class="C">
<span class="sc1">passtest</span>
<br/>
<em class="ec1">City1, State1</em>
</div>
</div>
<div class="A">
<div class="B">
<a href="/link1">
<img class="imgClass" src="http://link.com/img.img" title="imgTitle"/>
</a>
</div>
<div class="C">
<span class="sc1">failtest </span>
<br/>
<em class="ec1">City1, State1 </em>
</div>
</div>
<div class="A">
<div class="B">
<a href="/link1">
<img class="imgClass" src="http://link.com/img.img" title="imgTitle"/>
</a>
</div>
<div class="C">
<span class="sc1">passtest </span>
<br/>
<em class="ec1">City2, State2 </em>
</div>
</div>
I found this from Dive Into Greasemonkey:
var allDivs, thisDiv;
allDivs = document.evaluate("//div[#class='sponsoredlink']", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0; i < allDivs.snapshotLength; i++) {
thisDiv = allDivs.snapshotItem(i);
// do something with thisDiv
}
I am looking at this code as the starting point for what I want to do. But, I am just a user, not a coder.
I understand the logic I need is:
For each div where class="a" which does contain the text "passtest" and also does not contain "state1" do not display that div.
Here's a script that does that, using jQuery. The hard part is choosing the selectors.
// ==UserScript==
// #name Show State1 passes only.
// #include http://YOUR_SITE/YOUR_PATH/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
$("div.A") .hide ()
.has ("span.sc1:contains('passtest')")
.has ("em.ec1:contains('State1')")
.show ();
Note that :contains() is case-sensitive.
See the code in action at jsFiddle.

Categories