Javascript getelementbyid получить значение

.get Element By Id ( )

Метод объекта document , который позволяет найти элемент на веб-странице по его идентификатору (атрибут id ). Возвращает Element или null , если ничего не нашлось.

Пример

Скопировать ссылку «Пример» Скопировано

    

Привет, незнакомец!

let title = document.getElementById("title") console.log(title.textContent) // напечатает "Привет, незнакомец!"
html> head>head> body> h1 id="title">Привет, незнакомец!h1> script> let title = document.getElementById("title") console.log(title.textContent) // напечатает "Привет, незнакомец!" script> body> html>

Как понять

Скопировать ссылку «Как понять» Скопировано

Метод работает с DOM, который связан с HTML-разметкой. Если в HTML есть тег с атрибутом id , то его можно получить из JavaScript с помощью метода get Element By Id ( ) .

Спецификация HTML требует, чтобы в рамках одной страницы значения атрибутов id были уникальными. За счёт этого и работает метод get Element By Id ( ) — элемент с искомым идентификатором или один, или его нет. Такой поиск работает очень быстро.

На практике

Скопировать ссылку «На практике» Скопировано

Николай Лопин советует

Скопировать ссылку «Николай Лопин советует» Скопировано

🛠 С идентификаторами удобно работать, когда их немного. Они хорошо подходят для уникальных элементов на странице: единственного заголовка, элементов формы или самой формы. Не используйте идентификаторы для повторяющихся элементов — элементов списков, повторяющихся полей.

🛠 Скрипты, работающие с HTML, видят только ту разметку, которую уже распарсил браузер. Браузер парсит HTML сверху вниз. Если скрипт находится вверху страницы, то он не найдёт элементы ниже в странице — браузер их ещё не увидел и ничего о них не знает. Поэтому скрипты либо подключают в конце страницы, либо подписываются на событие DOM Content​ Loaded , которое сигнализирует о том, что браузер распарсил весь HTML.

🛠 Спецификация HTML требует уникальности идентификатора на странице, но сайт не сломается, если идентификаторы задублируются. До такого лучше не доводить, потому что поведение get Element By Id ( ) в этом случае не определено — метод может вернуть любой из элементов.

🛠 В отличие от других похожих методов: get Elements By Class Name ( ) и get Elements By Tag Name ( ) , метод get Element By Id ( ) есть только у объекта document .

Источник

Document: getElementById() method

The getElementById() method of the Document interface returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they’re a useful way to get access to a specific element quickly.

If you need to get access to an element which doesn’t have an ID, you can use querySelector() to find the element using any selector.

Note: IDs should be unique inside a document. If two or more elements in a document have the same ID, this method returns the first element found.

Syntax

Note: The capitalization of «Id» in the name of this method must be correct for the code to function; getElementByID() is not valid and will not work, however natural it may seem.

Parameters

The ID of the element to locate. The ID is a case-sensitive string which is unique within the document; only one element should have any given ID.

Return value

An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document.

Examples

HTML

html lang="en"> head> title>getElementById exampletitle> head> body> p id="para">Some text herep> button onclick="changeColor('blue');">bluebutton> button onclick="changeColor('red');">redbutton> body> html> 

JavaScript

function changeColor(newColor)  const elem = document.getElementById("para"); elem.style.color = newColor; > 

Result

Usage notes

Unlike some other element-lookup methods such as Document.querySelector() and Document.querySelectorAll() , getElementById() is only available as a method of the global document object, and not available as a method on all element objects in the DOM. Because ID values must be unique throughout the entire document, there is no need for «local» versions of the function.

Example

doctype html> html lang="en-US"> head> meta charset="UTF-8" /> title>Documenttitle> head> body> div id="parent-id"> p>hello word1p> p id="test1">hello word2p> p>hello word3p> p>hello word4p> div> script> const parentDOM = document.getElementById("parent-id"); const test1 = parentDOM.getElementById("test1"); // throw error // Uncaught TypeError: parentDOM.getElementById is not a function script> body> html> 

If there is no element with the given id , this function returns null . Note that the id parameter is case-sensitive, so document.getElementById(«Main») will return null instead of the element because «M» and «m» are different for the purposes of this method.

Elements not in the document are not searched by getElementById() . When creating an element and assigning it an ID, you have to insert the element into the document tree with Node.insertBefore() or a similar method before you can access it with getElementById() :

const element = document.createElement("div"); element.id = "testqq"; const el = document.getElementById("testqq"); // el will be null! 

In non-HTML documents, the DOM implementation must have information on which attributes are of type ID. Attributes with the name «id» are not of type ID unless so defined in the document’s DTD. The id attribute is defined to be of ID type in the common cases of XHTML, XUL, and others. Implementations that do not know whether attributes are of type ID or not are expected to return null .

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • Document reference for other methods and properties you can use to get references to elements in the document.
  • Document.querySelector() for selectors via queries like ‘div.myclass’
  • xml:id — has a utility method for allowing getElementById() to obtain ‘xml:id’ in XML documents (such as returned by Ajax calls)

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Получить значение value из тега input | JavaScript

document.getElementById() — поиск по тегу с атрибутом id

id на веб-странице может быть присвоен только один раз одному тегу HTML Задача: нужно вывести значение выбранного цвета рядом с полем ввода:

idColor" placeholder="введите текст"/> rezultatColor">  

document.getElementsByName() — поиск по NodeList тегов с атрибутом name

Задача: прибавить значение только третьего включенного чекбокса, округлить до сотых и показать в формате 0.00 (с двумя знаками после запятой):
1.00

name="nameCheckbox" value="1"/> name="nameCheckbox" value="20"/> name="nameCheckbox" value="300.555" onclick="onclickCheckbox()"/> name="nameCheckbox" value="400"/> 1.00  Пояснения: имеется четыре тега input с name="nameCheckbox". [0] - это первый по счёту, соответственно, [2] будет третьим.
nameRadio" value="1" checked="checked"/> nameRadio" value="20"/> nameRadio" value="300"/> nameRadio" value="400"/> 1  

document.getElementsByClassName() — поиск по NodeList тегов с атрибутом class

 .classGreen < background: green; width: 130px; height: 130px; margin: 0 auto; transition: .5s; >.classRed 
class="classGreen">

document.body — поиск по тегу body

document.body.innerHTML = document.body.innerHTML.replace(/\u003Ch2/g, '\u003Ch3');" /> Пояснения: я меняю , потому что тег может содержать атрибуты.  пишу как специальный символ в JavaScript \u003C.

document.getElementsByTagName() — поиск по NodeList тегов

h3')[4].innerHTML = 'Скрипт сработал\(\)'"/> Скрипт сработал\(\) - это то, на что мы заменяем наш текст. Он выглядит как Скрипт сработал(). Куда же делись символы \? Они реализуют экранирование скобок, чтобы те были рассмотрены как текстовые символы, а не как код скрипта. 
 Li(); setInterval(Li,1000); function Li() < d = new Date(); var month=new Array("января","февраля","марта","апреля","мая","июня","июля","августа","сентября","октября","ноября","декабря"); var week=new Array("воскресенье","понедельник","вторник","среда","четверг","пятница","суббота"); document.getElementById('d').getElementsByTagName('li')[0].innerHTML='Дата: '+d.getDate()+' '+month[d.getMonth()]+' '+d.getFullYear()+' года, '+week[d.getDay()]; document.getElementById('d').getElementsByTagName('li')[1].innerHTML='Время: '+((d.getHours()

document.querySelector() — поиск по селектору

Задача: показать степень заполнения полей, пароль и email должен быть внесён правильно.
Почта
Пароль

 input:focus:invalid < border: 1px solid #eee; >input:invalid Почта  
Пароль " title="Не менее 6 знаков, в том числе хотя бы одна цифра и буква" onchange="oninputEmail()"/>
0%

document.querySelectorAll() — поиск по NodeList селекторов

Помните этот пример? Там поиск идёт только по h3. Именно на него произойдет замена по этой кнопке. Если её не нажимать, то скрипт не будет работать. А вот так будет и при h2, и при h3

h2, h3')[4].innerHTML = 'Скрипт сработал\(\)'"/>

11 комментариев:

Анонимный Здравствуйте!
У меня вот такой вопрос. Не подскажите.
Есть 2 поля и две кнопки.
Я хочу VALUE кнопок передать в поля.

Просто значение например 1 кнопки передать в 1 поле понятно. Но хотелось бы. Что бы в поле попадало значение кнопки которую нажал. Не важно 1 или 2 или 11.

Вот что-то начал но дальше…

form
input type=»text» value=»1″
input type=»text» value=»2″
/form

input name=»poga2″ type=»button» value=»L» onclick=»q.value = fun()»
input name=»poga3″ type=»button» value=»M»

script
function fun() var per1=document.getElementById(‘q’).value;
var per2=document.getElementById(‘x’).value;

/script
Буду очень благодарен за подсказку.
До свидания.
NMitra Здравствуйте, пример http://jsfiddle.net/NMitra/dhj7epc4/

Анонимный Здравствуйте!
Спасибо Вам за ответ. Спасибо за помощь.
Анонимный Здравствуйте!
Подскажите как перебрать список с помощью javascript :
ul
li1/li
li2/li
li3/li
li4/li
li5/li
li6/li
li7/li
/ul

script
var el = document.querySelector(‘li’);

Источник

Читайте также:  Mailto links in html
Оцените статью