Reputation: 221
I have this function
function doSomething(elementID) {
$("div").append("<p id='"+ elementID +"'> A paragraph</p>");
/* this part is incorrect since it will
use the selector whose id is "elementID" and not the parameter passed. */
$("p#elementID").css("color", "red");
}
I want to do something like this but this is clearly incorrect. How do you use or store the selector using the ID parameter?
Something like this (but this is incorrect too):
var x = $("# '"+elementID+");
Upvotes: 1
Views: 53
Reputation: 450
Please Check this example below. You need to just change :
$("p#elementID").css("color", "red");
into
$("p#"+ elementID).css("color", "red");
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var elementID = "myid";
$("div").append("<p id='"+ elementID +"'> A paragraph</p>");
/* this part is incorrect since it will
use the selector whose id is "elementID" and not the parameter passed. */
$("p#"+ elementID).css("color", "red");
});
</script>
</head>
<body>
<div>
</div>
</body>
</html>
Hope this will be helpful for you.
Upvotes: 1
Reputation: 337560
There's two ways you can do this. The first is to use string concatenation - exactly as you already do when creating the element:
function doSomething(elementID) {
$('div').append('<p id="' + elementID + '"> A paragraph</p>');
$('p#' + elementID).css('color', 'red');
}
The second, and more preferable IMO, is to keep a reference to the element you created then use that in the second statement with appendTo()
:
function doSomething(elementID) {
$('<p id="' + elementID + '"> A paragraph</p>').css('color', 'red').appendTo('div');
}
Also note that it would be better practice to use a CSS class to set the color
of the element. Using css()
should be avoided where possible, as it ties the UI and JS code together too closely.
Upvotes: 3