Замена без innerHTML
Можно ли заменить на странице <h2>Zagolovok-1</h2>
не перерисовывая весь элемент в котором находиться h2 ? document.getElementById('div_id').innerHTML = document.getElementById('div_id'').innerHTML.repla ce('<h2>Zagolovok-1</h2>', '<h2>Zagolovok-2</h2>'); |
<html> <head> </head> <body> <h2>foo</h2> <h3>foo</h3> <script> document.querySelector("h2").innerHTML="baz" document.getElementsByTagName("h3")[0].innerHTML="baz" </script> </body> </html> |
Простите, забыл пояснить. Заменить именно конкретный элемент, он может быть любым, id у него нет, но знаем точно какой тег и что внутри.
типа так чтобы работало document.volshebhaya_hren("<h2>Zagolovok-1</h2>").innerHTML="<h2>Zagolovok-new</h2>" |
Цитата:
|
Цитата:
|
Может я что то не понимаю, Нужно проверять не только какой тег но и что там внутри, т.к .может быть несколько одинаковых тегов, а поменять надо только в одном
|
<html> <head> </head> <body> <h1>foo</h1> <h1>bar</h1> <script> ;[].forEach.call(document.querySelectorAll("h1"), function(el){if(el.innerHTML==="bar") el.innerHTML="baz"}) </script> </body> </html> если производительность критична, можно так <html> <head> </head> <body> <h1>foo</h1> <h1>bar</h1> <script> ;[].forEach.call(document.querySelectorAll("h1"), function(el){ try{ if(el.innerHTML==="bar") throw el }catch(e){e.innerHTML="baz"}}) </script> </body> </html> или тупо циклом <html> <head> </head> <body> <h1>foo</h1> <h1>bar</h1> <script> els=document.querySelectorAll("h1") for(var i=0; i<els.length; i++){ if(els[i].innerHTML==="bar") {els[i].innerHTML="baz" ; break} } </script> </body> </html> |
krutoy,
>если производительность критична, можно так >try catch Ты совсем больной? Исключения замедляют код на порядки. |
Aetae,
Ога arr=[] i=1000000 while(i--){arr.push(i)} i=1000000 withTry=function(name){ console.time(name) try{ arr.forEach(function(el) {if(el===1||el===(i-1)) throw el}) }catch(e){console.log(e)} console.timeEnd(name) } withOutTry=function(name){ console.time(name) arr.forEach(function(el) {if(el===1||el===(i-1)) console.log(el)}) console.timeEnd(name) } withTry("with") withOutTry("without") // ::: 999999 // ::: with: 2ms // ::: 999999 // ::: 1 // ::: without: 117ms И про память не забудь. Говностек никто не отменял. |
document.querySelector('#div_id h2').innerHTML = '...'; |
Переходите уже на новые стандарты :)
ES7: let number = +(prompt("Введите число.")); alert([1, 2, 3].includes(number)); Полифилл: if (![].includes) { Array.prototype.includes = function(searchElement/*, fromIndex*/) { if (this === undefined || this === null) { throw new TypeError('Cannot convert this value to object'); } var O = Object(this); var len = parseInt(O.length) || 0; if (len === 0) { return false; } var n = parseInt(arguments[1]) || 0; var k; if (n >= 0) { k = n; } else { k = len + n; if (k < 0) k = 0; } while (k < len) { var currentElement = O[k]; if (searchElement === currentElement || (searchElement !== searchElement && currentElement !== currentElement)) { return true; } k++; } return false; } } --- Крутой, чем твой вариант лучше "~[1, 2, 3].indexOf(number)"? |
Цитата:
<h1>Zagolovok-1</h1> <button>click</button> <script> document.querySelector("button").addEventListener("click", function () { var h1 = document.querySelector("h1"); if ( h1 ) { h1.outerHTML = "<h2>Zagolovok-2</h2>"; } alert(document.querySelector("h2").innerHTML); }); </script> PS: Erolast, забыл кнопку run |
А includes пока только в FF Nightly реализован. Вот вместе с полифиллом рабочий пример:
if (![].includes) { Array.prototype.includes = function(searchElement/*, fromIndex*/) { if (this === undefined || this === null) { throw new TypeError('Cannot convert this value to object'); } var O = Object(this); var len = parseInt(O.length) || 0; if (len === 0) { return false; } var n = parseInt(arguments[1]) || 0; var k; if (n >= 0) { k = n; } else { k = len + n; if (k < 0) k = 0; } while (k < len) { var currentElement = O[k]; if (searchElement === currentElement || (searchElement !== searchElement && currentElement !== currentElement)) { return true; } k++; } return false; } } alert([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].includes(+(prompt("Введите число от 1 до 10.")))); |
Часовой пояс GMT +3, время: 22:19. |