I'm trying to create simple selection option for users when selecting a particular font style. If they click on a font div, the background of that div should change color.
The problem I'm having is that the first font div works perfectly in changing color - however the other font divs do not follow suit.
JSFiddle
HTML
<div class="fonts">
<div id="font" class="minecraft-evenings">
Hello
<p>Minecraft Evenings</p>
</div>
<div id="font" class="minecrafter">
Hello
<p>Minecrafter 3</p>
</div>
<div id="font" class="volter">
Hello
<p>Volter</p>
</div>
</div>
JavaScript/JQuery
$(document).ready(function() {
$('#font').click(function() {
$(this).css("background-color", "#000");
$('#font').not(this).css("background-color", "#f1f1f1");
});
});
The problem:
ID's are meant to be unique identifiers. You should be using classes if you want to identify multiple elements. For this reason, when you select by ID with $("#font"), jQuery (which uses native javascript's getElementById) will only return the first element it comes across that has that ID. This is because if the DOM is valid, it shouldn't find anymore instances of that ID and it would be a waste of processing to continue looking.
A solution:
Remove the font ID's from your divs and replace them with a class instead, like class="font". Since you already have some classes identified, you can use multiple classes separated by spaces, like: class="font minecrafter". After doing this, you will be able to select your elements with the font class using this selector: $(".font")
Related
which option among the following is better or used as a standard way to show/hide the html elements
changing element.style.display
adding/removing a separate class called hide {display: none}
any other standard way
PS: this JavaScript hide/show element question uses the first option mentioned( changes the style to block to show which may not be desired). I would like to know whether this method is used in most websites or the adding /removing a separate class or any other way
A third way in the answers below https://stackoverflow.com/a/68983509/14478972
I prefer to toggle a class using DOMTokenList.toggle():
The toggle() method of the DOMTokenList interface removes a given token from the list and returns false. If token doesn't exist it's added and the function returns true.
Well except the first and second, there is the other way.
Which is rendering the element its self.
It has a better security. as the user wont know if there is a hidden element inside the toggle div. Eg when people try to look at the html
Have a look below
I used jQuery as its easier to write. If you are not able to rewrite a JavaScript version will be happy to rewrite for you.
var items = $(".toggle");
var item = {};
// setup the auto toggle
$(".toggle").each(function(el) {
var id = new Date().getUTCMilliseconds() + $(this).index()
item[id] = $(this).find("content")
if (!$(this).hasClass("show")){
$(this).find("content").remove();
}
$(this).attr("id", id)
});
$(".toggle").click(function() {
if ($(this).find("content").length > 0)
$(this).find("content").remove();
else $(this).append(item[$(this).attr("id")])
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toggle">
<h1>click here to toggle content </h1>
<content>
this is a test
</content>
</div>
<div class="toggle show">
<h1>click here to toggle content(start state is visible) </h1>
<content>
this is a test
</content>
</div>
Option 1 would be standard for only hiding the element, but if you would like to add other styles like transitions and pointer events option 2 is preferred
I know that is a bad practice to have more than HTML elements having same ID. However such is my situation where I need to specifically modify either of them.
I researched around and found about Jquery method 'document.getElementByID' that returns with the first similar element and lets you change it using css. Using that I wrote the code below but it doesn't work.
$(document.getElementById('it_trending-3')).css({"display":"none"});
I have added this code in my wordpress theme using the CSS-JS-PHP wordpress plugin, created a shortcut from the same and then added the shortcode. Can someone please guide me what and where I went wrong?
Also feel free to suggest a different function that would maybe let me specifically point to each of the same ID elements using maybe indexes. Thanks!
Keep a class to the divs you want to change:
<div>
<span id="a" class="test">1</span>
<span id="b" class="test">2</span>
<span>3</span>
</div>
The Jquery would go like this:
$(function() {
var w = $("div");
console.log($('#a').length);
console.log($('body #a').length);
console.log($('#a', w).length);
});
$(".test").first().css({"color":"orange"});
//or
$(".test:first").css({"color":"orange"});
But if you want to select any specific element with the class via an index of sorts, then you would need to do it like this:
var x = $(".test");
$(x[1]).css({"color":"orange"});
You can achieve this in 2 ways.
Based on element's hierarchy or based on class attribute / custom data attribute to the element.
In the below example we have 3 span elements with the same id and we have to apply 3 colors to each of those span elements.
HTML
<div>
<span id="it_trending-3">
Applying css to same Id with hierarchy (span in 1st div)
</span>
</div>
<div>
<span id="it_trending-3">
Applying css to same Id with hierarchy (span in 2nd div)
</span>
</div>
<br /><br /><br />
<span id="it_trending-3" class="testcls">
Applying css to same Id with class
</span>
Applying css using js / jquery based on element hierarchy
JQuery
(function($){
$("div:last #it_trending-3").css("color", "red");
$("div:first #it_trending-3").css("color", "green");
})(jQuery);
Based on class attribute / custom data attribute to the element.
JQuery
(function($){
$("#it_trending-3.testcls").css("color", "blue");
})(jQuery);
JS Fiddle Demo
I have some contenteditable divs with the same class, the div is dynamically created so I don't know how many there are.
<div class="scale1" onclick="document.execCommand('selectAll',false,null)" contenteditable>0</div>
<div class="scale1" onclick="document.execCommand('selectAll',false,null)" contenteditable>0</div>
<div class="scale1" onclick="document.execCommand('selectAll',false,null)" contenteditable>0</div>
I want the text in the last one to be selected (like if you hold the left mouse button down over the text) with a button
The obvious way in jquery:
$(".scale1:last").click();
Doesn't work, it selects the hole page.
I also thought about ways in javascript like Selection.selectAllChildren and Selection.addRange() but i have no elegant way of knowing the last div
How to make text selection checkout here
To reach your goal - replace ID selection with following code:
var query = document.querySelectorAll(".scale1"),
text = query[query.length-1];
Try:
$('.scale1:last').text()
or
$('.scale1').last().text()
Either would work, even for dynamically added elements.
DEMO
I'm on a site where I wanted to change my username color with javascript. I was able to change the background with getElementById but i cant seem to change the color of specific text without changing the whole page text color. Is there a way to use getElementById to change a specific text on the page?
Well, you could simply have each username enclosed within a <div> tag with an id of that user's id. And reference it that way with document.getElementById(). style.color
See this demo
<div> This div <span id="sp1">elements</span> have <span id="sp2">different</span> colours </div>
document.getElementById('sp1').style.color = 'green';
document.getElementById('sp2').style.color = 'red';
getElementById only gets the whole HTML element which contain the specific ID. So if you wish to style on the specific bunch of text inside that element, you can use inline elements for the specific text. For example:
<div id="text">
Some text with <span>your name</span> here.
</div>
Simply use CSS to style it rather than JavaScript:
div#text span {
color: blue;
}
This is possible only if you have the text wrapped by a node. Use span tag to contain the desire text. Include a class for the span like this <span class="username">user name here</span>. Then use in your CSS stylesheet :
span.username{
color : your.desired.color ;
}
I recommend you learn CSS if you are making a site. Is the best! If you don't want to use CSS you can just write <span style="color:red">user name here</span>. It will display the user name in red.
You can do something like this:
document.getElementById("id").style.color = "red";
DEMO: JSFiddle
I am working with the google maps drawing manager. They don't put id's or class names on the drawing tools button bar so I'm trying to do this myself.
First I want to remove the circle button which the below works fine, but I want to add my own button so need to add a class name to the parent div "gmnoprint" but google has about 5 div's all with the same class name. I just want to add it to the one where the circle button was found.
<div class=gmnoprint"></div>
<div class=gmnoprint"></div>
<div class=gmnoprint"></div>
<div class=gmnoprint">
<div>
<div> <== This is what I found in my search
<span>
<div>
<img></img>
</div>
</span>
</div>
</div>
</div>
I am able to find the element I want and remove it, but adding a class to its wrapper div is proving a bit difficult for me.
This works for removing the button
$(".gmnoprint").each(function(){
$(this).find("[title='Draw a circle']").remove();
});
This doesn't work.. Just add's the class to all ".gmnoprint" div's
$(".gmnoprint").each(function(){
$(this).find("[title='Draw a circle']").remove().parent().addClass("test");
});
remove() removes the element from the DOM and returns the free-standing jquery object which has no connection to the DOM at all. A call to parent() after calling remove() is incorrect and that likely is the cause for your issue.
Try splitting your statements to:
var toRemove = $(this).find("[title='Draw a circle']");
toRemove.parent().addClass("test");
toRemove.remove();
You can use jQuery insertAfter and out your button after that default button then remove it.
$(".gmnoprint").each(function(){
var defBtn = $(this).find("[title='Draw a circle']");
$('<button class="my-button" />').insertAfter(defBtn);
defBtn.remove();
});
Or use jQuery after like this:
$(".gmnoprint").each(function(){
$(this)
.find("[title='Draw a circle']")
.after($('<button class="my-button" />'))
.remove();
});
You can use child selector to target the elements
$(".gmnoprint > div > div").addClass('myClassName');
At that point you could replace the html of the whole div , or find the span and replace it's inner html. Using html() method you don't need to use remove() as it will replace all contents of the element(s)
$(".gmnoprint > div > div").addClass('myClassName').find('span').html('<newButton>');
API Reference : http://api.jquery.com/child-selector/