How do I select an embedded element with Javascript? - javascript

I need some help selecting the button in the example below. I am working with Wordpress and when I try to add a custom class to my button, it only adds it to the div that the button is in.
<div class="basic">
<button class="btn">Content</button>
</div>
Now I want to add some JS that changes the background color of the button when another button is clicked. When I select the div with the class assigned by me, the background color of the button doesn't change. I would have to select the button directly but I don't know how.
Any help is appreciated

There are several options to select the button:
querySelector
console.log(document.querySelector('.btn')); // Via its class name
console.log(document.querySelector('button')); // via its tag name
<div class="basic">
<button class="btn">Content</button>
</div>
querySelector returns the first matching element.
querySelectorAll returns all matching elements.
getElementsByClassName
console.log(document.getElementsByClassName('btn')[0]); // Select the first element, because getElementsByClassName returns a HTMLCollection!
<div class="basic">
<button class="btn">Content</button>
</div>
getElementsByTagName
console.log(document.getElementsByTagName('button')[0]); // Again select the first one!
<div class="basic">
<button class="btn">Content</button>
</div>
Now let's solve your problem:
// You can use either querySelector, getElementsByTagName, or getElementsByClassName. I decided for querySelector
function changeColor() {
document.querySelector('.btn').style.backgroundColor = "red";
}
<div class="basic">
<button class="btn">Content</button><button onclick="changeColor()">Change Color!</button>
</div>
Edit
If you want to select only the buttons whithin a specific div, you can do it this way:
function changeColor() {
var div = document.getElementsByClassName('basic')[0]; // Get the specific div
var buttons = div.getElementsByClassName('btn'); // Get the buttons by class, but only within the div
for (var i = 0; i < buttons.length; i++) { // Loop through the HTMLCollection and apply the CSS to every element
buttons[i].style.backgroundColor = "red";
}
}
<div class="basic">
<button class="btn">Content</button>
<button class="btn">Content</button>
<button class="btn">Content</button>
</div>
<button class="btn">I won't get selected</button>
<button onclick="changeColor()">Change color</button>

Related

How to get value inside a div element using JS

Here I have a div element with class med and I want to access the value inside the div of the Prescribed:{{pro_id.prescribedmed}} .I tried JS to get the value by using the getattribute() but it does not show. how can get the value of it. Here is the piece of code
<div class="column">
<!-- style="background-color:#bbb; -->
<p class="newarrival ">Rs.{{pro_id.price}}</p>
<h4>{{pro_id.name}}</h4>
<p><strong>Category:</strong> {{ pro_id.category}}</p>
<p><strong>Description:</strong> {{pro_id.smalldescription}}.</p>
<div class="med hidden" >
<p>Prescribed:{{pro_id.prescribedmed}}</p>
</div>
<button data-product={{pro_id.id}} data-action="add" type="button" class="btn-cart update-cart"> Add to cart
</button>
</div>
i tired to get the element like
var premed = document.getElementsByClassName('med').innerText;
console.log(premed)
here the output gives like undefined
Give this a try
<p class="med_prescribed">Prescribed: {{ pro_id.prescribedmed }}</p>
in your JS as follows
var premed = document.getElementsByClassName('med_prescribed')[0].innerText;
console.log(premed);
If I had to do that it would look next:
First select the element with Document.querySelector().
Then extract the text of the element.
And finally use the String.prototype.substring() method to get the needed value.
You cant get the attribute because you dont have one.
Div element:
<div class="med hidden" id="Div_id" value="Value_here" >
JS:
var value = document.getElementById("Div_id").getAttribute ("value")

Find document element by class name closest to the button that is being clicked

I have a little mini html game that uses Backbone.
The main page has multiple <div> tags with the class name of "monsterName".
There is a button near it, that, when clicked, I want to get the text that is inside the "monsterName" <div>
I am trying to use the closest() method from the WebAPI to find the closest <div> to the clicked button that has a class name of "monsterName".
Here this will help you see my HTML page generated by the view and template:
<div id="root">
<div id="title">Monster Hunting 101</div>
<div class="monsterArea">
<div class="monsterName">Orc</div>
<div class="controls">
<button class="findMonster">Monster Hunting</button>
</div>
</div>
<div class="monsterArea">
<div class="monsterName">Dragon</div>
<div class="controls">
<button class="findMonster">Monster Hunting</button>
</div>
</div>
<div class="monsterArea">
<div class="monsterName">Giant</div>
<div class="controls">
<button class="findMonster">Monster Hunting</button>
</div>
</div>
The view has code that fires when the button ".findMonster" is clicked:
events: {
"click .findMonster": "startHunt"
},
When that button is clicked, it fires this function:
startHunt: function (e) {
const $closestMonster = e.closest('.monsterName');
console.log($closestMonster.innerHTML);
...do some stuff with the text in the monsterName...
}
So the view is working and the button works, and it fires off the startHunt event.
But it always gives me this error:
Uncaught TypeError: e.closest is not a function
A combination of closest() and find() worked for this problem:
const $closestMonster = e.closest('.monsterArea').find('.monsterName');

How to get text for div close to button clicked

I'm trying to get the text of some div within the parent div where button is clicked. This is an example code
<div class="parentDiv" >
<div id="divToFind" style="display:none">text</div>
<div class="btn-group">
<button class="button" type="button" >Remove</button>
</div>
</div>
<div class="parentDiv" >
<div id="divToFind" style="display:none">text2</div>
<div class="btn-group">
<button class="button" type="button">Remove</button>
</div>
</div>
Here parentDiv is repeated couple of times and text of divToFind is different in each parentDiv. Whenever remove button is clicked within the parentDiv I want to get the text of divToFind.
I have tried this
$(this).closest('.parentDiv').children('#divToFind').text();
But nothing is returned
Don't use same IDs in a single document. You should use classes instead. With class, it works fine.
It is mentioned in the spec that there must not be multiple elements in a document that have the same id value.
$(function(){
$("button").on("click", function(){
var t = $(this).closest('.parentDiv').children('.divToFind').text();
console.log(t);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parentDiv" >
<div class="divToFind" style="display:none">text</div>
<div class="btn-group">
<button class="button" type="button" >Remove</button>
</div>
</div>
<div class="parentDiv" >
<div class="divToFind" style="display:none">text2</div>
<div class="btn-group">
<button class="button" type="button">Remove</button>
</div>
</div>
Yes, Its true, you should not use same Id for 2 elements in an HTML document, However following is the code that can help you to get the text of the div given.
There are 2 ways:
$(this).parent().prev('#divToFind').text();
$(this).parent().prev().text();
prev and next allows us to traverse on the same level. You can provide selectors inside that to get particular element.
In your example its ID, you can update Id to some css class, so that you dont have to have elments with same ID.

Toggle individual divs in a loop

In rendering out data within HTML, which prints out a div down the page, for every row found in the database, I'm trying to find a way to allow each button that sits in each div to toggle the individual example when clicked (with a default of display:none upon loading the page) - something such as:
function toggle_div(id) {
var divelement = document.getElementById(id);
if(divelement.style.display == 'none')
divelement.style.display = 'block';
else
divelement.style.display = 'none';
}
An example of the final markup :
<div>
<div class="wordtitle">Word</div>
<div class="numbers">1</div>
<div class="definition">Definition</div>
<button class="button" id="show_example" onClick="toggle_div('example')">Show example</button>
<div class="example" id="example">Example 1</div>
</div>
<div>
<div class="wordtitle">Word</div>
<div class="numbers">2</div>
<div class="definition">Definition</div>
<button class="button" id="show_example" onClick="toggle_div('example')">Show example</button>
<div class="example" id="example">Example 2</div>
</div>
getElementById() only toggles the first div's example, and getElementsByClass() hasn't seemed to work so far - not too sure how to do this - any ideas much appreciated!
First rule, do not insert multiple elements with the same ID. IDs are meant to be unique.
What you need is to toggle the example near the button you clicked, and not any (or all) .example to be showed / hidden. To achieve this, considering you used the [jquery] tag in your question, you can either use a selector to get the nearest .example of your button, or use jQuery's built-in functions to get it (.siblings()).
I would personally put the onclick out of your markup, and bind this custom function in your javascript.
Another important thing : if javascript is disabled client-side, the user won't ever see your example, as they are hidden by default in CSS. One fix would be to hide it initially with JS (see the snippet for this).
Here's a demonstration of what I mean :
$('.example-trigger').click(function() {
//Use the current button which triggered the event
$(this)
//Find the sibling you want to toggle, of a specified class
.siblings('.example-label')
//Toggle (hide or show) accordingly to the previous display status of the element
.toggle();
});
//Encouraged : hide examples only if Javascript is enabled
//$('.example-label').hide();
.example-label {
display: none;
/* Discouraged : if javascript is disabled, user won't see a thing */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
<button class="example-trigger">Toggle example 1</button>
<span class="example-label">Example 1</span>
</div>
<div>
<button class="example-trigger">Toggle example 2</button>
<span class="example-label">Example 2</span>
</div>
<div>
<button class="example-trigger">Toggle example 3</button>
<span class="example-label">Example 3</span>
</div>
As #Sean stated, you need the ID to be unique since that's the way you are getting your elements.
$words .= '<div class="wordtitle">' . $word .'</div>
<div class="numbers">' . $i . '</div>
<div class="definition">' . $definition . '</div>
<button class="button" id="show_example" onClick="toggle_div(\'example\''.$i.')">
show example</button>
<div class="example" id="example'.$i.'">' . $example . '</div>
<br/><br/>';
$i++;
#show_example will also be repeating so you will probably want to change that to a class.
Another answer, only because I had the answer ready and was called away before I could post it. So here it is.
Notice that for repeating elements, classes are used instead of IDs. They work just as well, and (as everyone else has already said), IDs must be unique.
jsFiddle demo
HTML:
<div class="def">
<div class="wordtitle">Aardvark</div>
<div class="numbers">1</div>
<div class="definition">Anteater</div>
<button class="button show_example">show example</button>
<div class="example" id="example">The aardvark pushed its lenghty snout into the anthill and used its long, sticky tongue to extract a few ants.</div>
</div>
<div class="def">
<div class="wordtitle">Anecdote</div>
<div class="numbers">2</div>
<div class="definition">Amusing Story</div>
<button class="button show_example">show example</button>
<div class="example" id="example">The man told an anecdote that left everyone laughing.</div>
</div>
jQuery:
var $this;
$('.show_example').click(function() {
$this = $(this);
if ( $this.hasClass('revealed') ){
$('.example').slideUp();
$('.show_example').removeClass('revealed');
}else{
$('.example').slideUp();
$('.show_example').removeClass('revealed');
$this.parent().find('.example').slideDown();
$this.addClass('revealed');
}
});

selecting span value inside div

Let's say I have
<div id="1">
<span id="name">Josh</span>
<div id="quote">Run</div>
</div>
<div id="2">
<span id="name">Mark</span>
<div id="quote">Run</div>
</div>
How would I select the name between the span tags from the first div?
$("#quote").click(function(){
var name = $('#name').html();
});
Firstly, id's have to be unique in an html document. So,ideally, you need to change those id's within the div to a class. Secondly, id's cannot begin with a numeric, so you need to change your div id's to start with a letter or underscore.
With that in mind, given this structure:
<div id="one">
<span class="name">Josh</span>
<div class="quote">Run</div>
</div>
<div id="two">
<span class="name">Mark</span>
<div class="quote">Run</div>
</div>
you would be looking for:
$("#quote").click(function(){
var name = $('#one .name').html();
});
id's should be unique across a page. You should change the name and quote id's to a class, which do not have to be unique.
<div id="1">
<span class="name">Josh</span>
<div class="quote">Run</div>
</div>
<div id="2">
<span class="name">Mark</span>
<div class="quote">Run</div>
</div>
You could then select via:
$('#1 .name')
You should also bare in mind that id's should not start with a number (except in HTML5)
var name = $("#1 span").html()
or
var name = $('#1 #name').html();
this should work for you:
$("#1 span").text();
You have some problems with your HTML though. You should not have any duplicate IDs in your HTML, they must be unique. ID shouldn't start with a number either.
You can view the fiddle here: http://jsfiddle.net/
you can select the first span tag content of your div #1 this way as well :
var name = $("#1 span:first").html();
Adding #1 before #name would select the first div
$("#quote").click(function(){
var name = $('#1 #name').html();
});

Categories

Resources