jQuery background changing with id - javascript

here thisid stores the id of html element. and I want to change its background colour using the following code
let thisid = 'test';
$("a#" + thisid).css("background-color", "yellow");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="test" href="#">Hello world!</a><br/>
<a id="test2" href="#">Goodbye all</a>
this is not working, but it works if I remove thisid and write it in following way
$("a").css("background-color","yellow");
but it selects all with tag
below is what actually I want to do.
$(document).ready(function() {
// hide all questions
$("h1").hide();
// display first question
$("h1#1").show();
// show selected question
$("a").bind('click',function(){
let thisid = $(this).attr('id');
$("h1").hide();
$("h1#"+thisid).show();
$("a#"+thisid).css("background-color","yellow");
});
});

The argument to the jQuery function ($()) is being treated as a CSS selector. Since you're trying to find an element by ID, you need to start the selector with an octothorpe (#). Starting with a character selects by tag type. Not having your html handy, I'm guessing the actual problem is that the element with ID thisid is not an <a> tag. (You're actually selecting "any a tag with id thisid", but since an ID is unique including the tag type selector is redundant)
You should be able to do something more like this:
let thisid = "two"
$("#"+thisid).css("background-color","yellow");
thisid = "three"
// won't work, element with id `three` is not an 'a' tag
$("a#"+thisid).css("background-color","green");
thisid = "four"
$("div#"+thisid).css("background-color","blue");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one">one</div>
<div id="two">two</div>
<div id="three">three</div>
<div id="four">four</div>

Related

JQuery clone is not working with class selector

Fiddle
I am trying to clone a span from the onClick() function of a button. First time this works fine but when I try second time it is not cloning. What am I doing wrong?
Here is the essence of my code.
$(document).ready(function(){
$('.addmachinerow').on('click',function(){
var edcname = $('.edc_name option:selected').val();
var machine_description = $("input[name='machine_description'").val();
var capacity = $("input[name='capacity'").val();
var voltage_level = $("input[name='voltage_level'").val();
var powertype = $("select[name='typeofpower'").val();
var edcautovalue = $('.ecaddingspan').attr('data-value');
//if($('#bank_increment').html() == '') $('#bank_increment').html('0'); else $('#bank_increment').html(parseInt($('#bank_increment').html())+1);
//if($('#bank_clickededit').html() == '') var bank_increment = $('#bank_increment').html(); else var bank_increment = $('#bank_clickededit').html();
$('.ecaddingspan').clone().appendTo('.edcparent');
//$('.bankname, .bankbranch , .IFSCcode , .bankaccno , .accsincefrom').val('');
var edc_details = {'edcname' : edcname, 'machine_description' : machine_description, 'capacity' : capacity, 'voltage_level' : voltage_level, 'powertype' : powertype }
//$('.bank_details_array').append(JSON.stringify(bank_details)+'&&');
});
});
Additionally:
How can i clone the entire sets on clicking the Total clone button ?
I need to save the values in array with different names. Is that possible ?
How can i clone the entire sets on clicking the Total clone button ?
You've to use event delagtion on() instead :
$('body').on('click','.addmachinerow', function(){
//Event code
})
Since the new .addmachinerow added to the page dynamically after the clone.
I need to save the values in array with different names is that possible ?
I suggest the use of the array name [] like :
<input name='machine_description[]' />
<input name='voltage_level[]' />
Hope this helps.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$('.cloneitem').not('.cloned').clone().addClass('cloned').appendTo('body');
});
});
</script>
</head>
<body>
<p class="cloneitem">This is a paragraph.</p>
<button>Clone all p elements, and append them to the body element</button>
</body>
</html>
The issue is a common misconception of JQuery selectors. If you play with ID selectors then switch to class selectors then you often don't notice a difference in behaviour. The ID selector doc says
ID Selector: If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM
whilst for the class selector
Class Selector: Selects all elements with the given class.
What this means is that when you clone the target element you get away with a subsequent ID selection (JQuery ignores the duplicates) but a subsequent class selection will trip you up if you were not expecting JQuery to return multiple matches. Class selectors are great for grouping elements but not so great for cloning.
While I am on the soap box - whenever you use the clone function you should consider and fix the potential duplicate ID and un-required class duplicates that you are producing. Duplicate ID's are definitely bad show - duplicate classes may actually be by design but you should still consider them.
In the code sample below I assign the class iAmSpartacus to the original span which the onClick() function then clones. Each clone also gets the iAmSpartacus class so I remove it from each new clone to ensure that the $(".iAmSpartacus") selector always returns a maximum of one element. The spans show their current class property to prove the point.
// this runs one - shows us classes of original span
var origSpan=$(".iAmSpartacus")
origSpan.html("My classes are: " + origSpan.prop("class"))
$("#daButton").on("click", function(e) {
var newSpan = $(".iAmSpartacus").clone();
newSpan.removeClass("iAmSpartacus"); // remove the dup targetting class
newSpan.appendTo('.edcparent');
newSpan.html("My classes are: " + newSpan.prop("class"))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="daButton">Click me</button>
<div class="edcparent" style="border: 1px solid red;">
<span class="ecaddingspan iAmSpartacus" style="display: block;">I am a span</span>
</div>

How to get class name of element has specific text using javascript/jquery?

I need a JavaScript or jQuery way of extracting the Class name of DIV element by the text it contains.
Let's illustrate. If I had let's say following code:
<div class="_className">UniqueText</div>
I need to to know how to programmatically do something like this:
getClassNameWhereText("UniqueText");
In this case output should be:
_className
Is there a way to do this?
JQuery :contains selector select element has specific text but it isn't exact. For example
$("div:contains(UniqueText)")
Select both of bottom divs
<div class="_className">UniqueText</div>
<div class="_className2">UniqueText2</div>
You can use .filter() to filter selected element by text.
var className = $("*").filter(function(){
return $(this).text() == "UniqueText";
}).attr("class");
var className = $("*").filter(function(){
return $(this).text() == "UniqueText";
}).attr("class");
console.log(className);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="_className">UniqueText</div>
<div class="_className2">UniqueText2</div>
By getting all the div with each function you can search through all the divs and place a condition in which you the value of the div is equal to the particular text that you want to find. Then get the class name by using .attr('class').
$( "div" ).each(function(){
if($(this).text() == "UniqueText"){
var output = $(this).attr('class');
$(".output").html(output);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="_classname">UniqueText</div>
<div class="output"></div>
It might be a bit long for a code but it gets the work done nicely. :)
You can use :contains(word)
var className = $( "div:contains('John')" ).attr("class");
console.log(className)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">John Resig</div>
<div class="bar">George Martin</div>
<div class="foo">Malcom John Sinclair</div>
<div class="baz">J. Ohn</div>
You can keep an id for your div, as per your information your text will be unique.
<div id="UniqueText" class="_className">UniqueText</div>
and the js code will be
function getClassNameWhereText(text){
var className = $('#'+text).attr('class');
console.log(className);
}
UPDATE : if you want to using contains
then you can do this,
function getClassNameWhereText(text){
var val = document.getElementById(text).value;
if(text.indexOf(val)>=0){
var className = $('#'+text).attr('class');
console.log(className);
}
}
This should be faster than using jQuery (but a bit more to type):
var xpath = "//div[text()='UniqueText']";
var result = document.evaluate(xpath,
document, null, XPathResult.FIRST_ORDERED_NODE_TYPE);
var node = result.singleNodeValue;
if (node) {
console.log(node.className);
} else {
console.error("Not found!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="_className">UniqueText</div>
The reason is, browser's CSS selectors don't support :contains selector, and jQuery needs to emulate it by checking every node matching the rest of the selector. Ditto for using .filter. But XPath is done natively by the browser.
You also cannot specify exact match using the jQuery :contains, like here. If substring matching was indeed needed, you can change the XPath:
var xpath = "//div[contains(text(),'UniqueText')]";
XPath is very powerful, but a bit finicky and largely unknown, so I find it is very under-utilised, even when its use would be a perfect fit.

Unable to get offset of an element

I am trying to get offset of some elements which is working fine for me. But the problem occurs if element id contains single quotes. It throw an error, e.g, if the element id is whats_next its working fine.
But if id is what's_next if gave me an error.
Error: Syntax error, unrecognized expression: #What's_Next
....value:null},t.error=function(e){throw new Error("Syntax error, unrecognized exp...
Also I don't have access over HTML I can not change the HTML. Do you guys have any solution for this ?
Here is my code:
$('.custom-toc li a').click(function(){
var id = $(this).attr('href');
console.log(id);
console.log($(id).offset());
});
HTML of element where I am clicking:
<a rel="internal" href="#What's_Next">What's Next</a>
HTML of element offset element:
<span id="What's_Next"></span>
<h4 class="editable">What's Next2</h4>
You can escape ' using replace()
HTML:
<div class="custom-toc">
<ul>
<li>
dddfs
</li>
</ul>
</div>
<span id="What's_Next">hello</span>
<h4 class="editable">What's Next2</h4>
JS :
$('.custom-toc li a').click(function(){
var id = $(this).attr('href').replace(/([ #;&,.+*~\':"!^$[\]()=>|\/#])/g,'\\$1');
console.log(id);
console.log($(id).offset());
});
Have you tried going for the id as attribute approach?
Like this:
var id = "What's Next";
var elem = $("span[id="+id+"]");
Well I tried, and it doesn't work :) - Cudos to Garvit, he has it right, this is his solution (only simplified):
var id = $(this).attr('href');
console.log(id);
id = id.replace("'","\\'");
console.log($("#"+id).offset());
Here's another way to do it without escaping the quote, although it requires you to remove the hash from the front of the href (and also, using $("*") is slow)
$('.custom-toc li a').click(function() {
var href = $(this).attr('href').substring(1);
var a = $("*").filter(
function(index) {
return $(this).attr('id') == href;
}
);
console.log($(a[0]).offset());
You can't use the ' symbol inside your div's id - You should change
<span id="What's_Next"></span>
to
<span id="Whats_Next"></span>
EDIT:
because You can't/don't want to change div's id You are working on an invalid code. You should consider debugging it first to further work.
EDIT 2:
Thanks to #Tibrogargan comment I've checked the w3c recommendation and he's probably right:
id = ID A unique identifier for the element. There must not be
multiple elements in a document that have the same id value. Any
string, with the following restrictions:
must be at least one character long
must not contain any space characters
Source: w3c.org

change url using jquery for specific css classes

I am using below code to covert all links in a page - Now i want this conversion to happen only for certain parts of page and not for complete page. I am sure this can be done to specific div tags
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$( document ).ready(function() {
$("a[href^='http']").each(function() {
var value = $(this).attr('href');
$(this).attr('href','<url>/pqr.php?'+value);
});
});</script>
Please suggest how can i achive this link conversion for specific div tags.
Example to explain problem statement - Consider following code snippet on which url conversion is required for only class="testclass"
<div class="messageContent">
<article>
<blockquote class="messageText SelectQuoteContainer ugc baseHtml">
<div class="testclass">
Amazon 1
</div>
<i>eps</i><br>
<span style="text-decoration: underline"><b><i>How to avail this offer </i></b></span><br>
<i>Add product into the cart<br>
Login or register<br>
Enter your shipping details<br>
Make the Final Payment.</i><br>
<span style="text-decoration: underline"><span style="font-size: 12px"><b>link</b> </span></span><br>
Amazon 2
<div class="messageTextEndMarker"> </div>
</blockquote>
</article>
</div>
I want to convert only the first url (AMAZON 1) and not the second url (AMAZON 2)
Test snippet on js fiddle - http://jsfiddle.net/bontp6jk/4/
What you want to do is first define the parent class and then for that class select all the link elements.
In jQuery you can use multiple selectors that works as follows:
$("#test") // select div 'test'
$(".myClass") // select class 'myClass'
$(".myClass #test") // select div 'test' in class 'myClass'
$("a") // select all link elements
Therefore, what you need is the following: $(".testclass a") which selects all link elements in the class .testclass. Then you can use jQuery .each() function to do something with the link elements.
$( document ).ready(function() {
$(".testclass a").each(function() {
var value = $(this).attr('href');
alert(value);
});
});
jsFiddle
Try this
$( document ).ready(function() {
$("a[href^='http']").each(function() {
var $this = $(this);
var value = $this.attr('href');
if($this.closest('.testclass').length!==0){
$this.attr('href','http://test.com/url.php?url=' + value + '&uid=test&origin=forum');
$this.attr("target","_blank");
}
});
});

Cloning div with unique ID doesn't work

I'm pretty sure I'm close but I don't know what I'm missing:
var newId = 1;
$("#trigger").click(function(){
$("#new-div").attr('id', 'new-div' +newId++).clone().appendTo("#myDiv");
});
I set breakpoints: I can see the counter auto-incrementing, but the cloned div does not appear where it should. I get no errors. HTML for this:
<div id="secret-div" style="display: none;">
<div>This is new div number </div>
</div>
<p><a id="trigger" href="javascript:void(0);">Please, add an element</a></p>
<div id="myDiv"></div>
The issue is that you're changing the ID of your element before cloning and appending, resulting in 2 elements with the same ID, breaking your selector and code.
Fixed Live Demo
HTML:
<div id="secret-div" style="display:none;">
<div>This is new div number <span class="spnNewDivNumber"></span></div>
</div>
<p><a id="trigger" href="javascript:void(0);">Please, add an element</a></p>
<div id="myDiv"></div>​
JavaScript:
var newId = 1;
$("#trigger").click(function() {
var $newSecretDiv = $("#secret-div").clone().attr('id', 'new-div' + newId++);
$newSecretDiv.show().appendTo("#myDiv");
$newSecretDiv.find('.spnNewDivNumber').text(newId - 1);
});​
Your current code is applying the new id before the clone, which means it's changing the id of the existing div. This in turn means that the next time the click handler is called, there won't be a div matching the selector '#new-div'.
Try applying the id after either the clone, or after inserting it into the DOM:
var newId = 1;
$("#trigger").click(function(){
$("#new-div").clone().attr('id', 'new-div' +newId++).appendTo("#myDiv");
});
OR
var newId = 1;
$("#trigger").click(function(){
$("#new-div").clone().appendTo("#myDiv").attr('id', 'new-div' +newId++);
});
You are attempting to clone the #new-div unless your current div is named 'new-div'. Also you are changing the id of the original div rather than creating a new one with the generated id.

Categories

Resources