jQuery Tutorial Tutorials - jQuery ID selector ('#ID')

jQuery ID selector ('#ID')

ID selector selects a single element with the given id attribute in the DOM.
ID selector syntax:

$('#some-id')

jQuery ID selector Example

In this example,when the user click the button, the element with id="myDiv" will be added a red border.

exampel:Select element by id using jQuery

<div id="div1">id="div2"</div>
<div id="div2">id="div2"</div>
<div id="myDiv">id="myDiv"</div>
<button>Add a border to myDiv</button>
<script>
$('#myDiv'); // [<div id="myDiv">id="myDiv"</div>]
$('button').click(function(){
    $('#myDiv').css( 'border', "2px solid red" );
});
</script>

If the ID has a special characters, we should use an escape character in selector.

<div id="foo.bar">DIV1</div>
<div id="foo[bar]">DIV2</div>
<div id="foo:bar">DIV3</div>

<script>
    console.log($('#foo\\:bar').length); // 1
    console.log($('#foo\\[bar\\]').length); // 1
    console.log($('#foo\\.bar').length); //1
</script>

Try now

Date:2019-06-09 01:28:04 From:www.Lautturi.com author:Lautturi