{"id":99,"date":"2021-07-22T16:42:21","date_gmt":"2021-07-22T16:42:21","guid":{"rendered":"https:\/\/the-js-source.flywheelsites.com\/?p=99"},"modified":"2021-09-29T18:05:38","modified_gmt":"2021-09-29T22:05:38","slug":"selecting-an-element-by-id","status":"publish","type":"post","link":"https:\/\/javascriptsource.com\/selecting-an-element-by-id\/","title":{"rendered":"Selecting an Element By Id"},"content":{"rendered":"\n

Select an element that matches the id using the getElementById() method.<\/p>\n\n\n\n

To get an element by id, you use the getElementById()<\/code> method of the Document<\/code> object:<\/p>\n\n\n\n

let element = document.getElementById(id);<\/code><\/pre>\n\n\n\n

The method returns an element whose id matches a specified string. <\/p>\n\n\n\n

The id<\/code> is case-sensitive. If no matching element was found, the method returns null<\/code>.<\/p>\n\n\n\n

Since the id<\/code> is supposed to be unique, using the getElementById()<\/code> method is a fast way to select an element.<\/p>\n\n\n\n

If the element does not have an ID, you can use the querySelector()<\/a><\/code> to find the element using any CSS selector.<\/p>\n\n\n\n

See the following example:<\/p>\n\n\n\n

<html>\n<head>\n  <title>JavaScript getElementById() example<\/title>\n<\/head>\n<body>\n  <h1 id=\"message\">JavaScript getElementById() Demo<\/h1>\n  <div id=\"btn\">\n    <button id=\"btnRed\">Red<\/button>\n    <button id=\"btnGreen\">Green<\/button>\n    <button id=\"btnBlue\">Blue<\/button>\n  <\/div>\n  <script src=\"js\/app.js\"><\/script>\n<\/body>\n<\/html><\/code><\/pre>\n\n\n\n
const changeColor = (newColor) => {\n    const element = document.getElementById('message');\n    element.style.color = newColor;\n}\n\nlet div = document.getElementById('btn');\n\ndiv.addEventListener('click', (event) => {\n    let target = event.target;\n    switch (target.id) {\n        case 'btnRed':\n            changeColor('red');\n            break;\n        case 'btnGreen':\n            changeColor('green  ');\n            break;\n        case 'btnBlue':\n            changeColor('blue');\n            break;\n    }\n});<\/code><\/pre>\n\n\n\n

Source<\/h2>\n\n\n\n