Html span text javascript

Как изменить текст элемента span в JavaScript

Перед тем, как показывать любую предоставленную пользователем строку таким образом, вы должны сначала убедиться, что она не содержит разметки HTML, в противном случае могут возникнуть проблемы с безопасностью (XSS).

@Gregoire имейте в виду, что ваше решение не работает на ie8 по крайней мере. См. Stackoverflow.com/questions/2119300/…

@gregoire — Как уже отмечали другие, ваш ответ уязвим для XSS. Этот вопрос уже просматривался около 80 тыс. Раз, что означает, что многие люди, вероятно, приняли это решение и могли внести ненужные утечки xss. Не могли бы вы обновить свой ответ, чтобы вместо этого использовать textContent , чтобы новым людям было предложено использовать правильные и безопасные методы?

@Tiddo textContent не поддерживается в IE8 и ниже, и я надеюсь, что вы никогда не будете использовать в своем скрипте напрямую необработанный пользовательский ввод.

Совет: не помешает взглянуть на следующую запись в блоге: Бедный, неправильно понятый innerText Отличная статья, чтобы получить представление о различиях между .innerText и .textContent , производительности, а также о том, что происходит «за кадром». Немного важной информации, IMO. 🙂

Использование innerHTML НЕ РЕКОМЕНДУЕТСЯ. Вместо этого вы должны создать textNode. Таким образом, вы «привязываете» свой текст, и вы, по крайней мере, в этом случае не уязвимы для атаки XSS.

document.getElementById("myspan").innerHTML = "sometext"; //INSECURE!! 
span = document.getElementById("myspan"); txt = document.createTextNode("your cool text"); span.appendChild(txt); 

Дополнительные сведения об этой уязвимости: Cross Site Scripting (XSS) — OWASP

Отредактировано ноябрь 4th 2017:

Изменена третья строка кода в соответствии с предложением @mumush: «используйте appendChild() вместо».
Кстати, согласно @Jimbo Jonny, я думаю, что все должно рассматриваться как пользовательский ввод, применяя принцип безопасности по слоям. Таким образом, вы не встретите никаких сюрпризов.

Хотя вы абсолютно правы в отношении innerHTML требующего осторожности, обратите внимание, что ваше решение использует innerText который не поддерживается в Firefox. quirksmode.org/dom/html Он также использует textContent который не поддерживается в IE8. Вы можете структурировать код, чтобы обойти эти проблемы.

Вопрос ничего не говорит о пользовательском вводе, поэтому общее утверждение о том, что innerHTML не рекомендуется, смешно. Не говоря уже о том, что после дезинфекции все в порядке. Идея, что нужно дезинфицировать пользовательский ввод, ТАК НЕ ОТНОСИТСЯ к этому конкретному вопросу. Самое большее, в конце он заслуживает небольшую заметку, гласящую: «Кстати, если это пользовательский ввод, сначала обязательно выполните дезинфекцию или используйте метод X, который в этом не нуждается» .

Использование appendChild на самом деле не меняет текст, а только добавляет к нему. Используя ваш код здесь, промежуток от исходного вопроса в конечном итоге будет читать «hereismytextyour your text text». Возможно span.innerHTML = «»; тогда appendChild?

document.getElementById('myspan').innerHTML = 'newtext'; 

EDIT: Это было написано в 2014 году. Вероятно, вы больше не заботитесь о IE8 и можете забыть об использовании innerText . Просто используйте textContent и textContent с ним, ура.

Читайте также:  seodon.ru - Условные комментарии IE

Если вы подаете текст, и никакая часть текста не предоставляется пользователем (или другим источником, который вы не контролируете), то установка innerHTML может быть приемлемым:

// * Fine for hardcoded text strings like this one or strings you otherwise // control. // * Not OK for user-supplied input or strings you don't control unless // you know what you are doing and have sanitized the string first. document.getElementById('myspan').innerHTML = 'newtext'; 

Однако, как отмечают другие, если вы не являетесь источником какой-либо части текстовой строки, использование innerHTML может подвергать вас атакам, связанным с innerHTML контента, например, XSS, если вы не будете осторожны, чтобы сначала дезинформировать текст.

Если вы используете ввод от пользователя, вот один из способов сделать это безопасно, одновременно поддерживая совместимость между браузерами:

var span = document.getElementById('myspan'); span.innerText = span.textContent = 'newtext'; 

Firefox не поддерживает innerText и IE8 не поддерживает textContent поэтому вам нужно использовать оба textContent если вы хотите поддерживать совместимость между браузерами.

И если вы хотите избежать переплавов (вызванных innerText ), где это возможно:

var span = document.getElementById('myspan'); if ('textContent' in span) < span.textContent = 'newtext'; >else

Источник

Injecting HTML text into a span using JavaScript

To achieve this, you can remove the node value and replace it by creating a new child element with the value of the parent item’s node. Finally, append the newly created element (span in this case) to the parent (paragraph in this case). :P) An alternative approach is to merge the following two tutorials: PPK on JavaScript: The DOM — Part 3 and Adding elements to the DOM.

Span to input text to span [duplicate]

Check out this simplified reference that could be useful to you: http://jsfiddle.net/RUwtt/.

$(function () < $('span').live('click', function () < var input = $('', ); $(this).parent().append(input); $(this).remove(); input.focus(); >); $('input').live('blur', function () < $(this).parent().append($('').html($(this).val())); $(this).remove(); >); >); 

The ‘contenteditable’-attribute is supported by certain browsers, enabling users to edit content by simply clicking on the element. By capturing the focus and blur events of editable elements, any changes made can be saved.

Check out the contenteditable demo by visiting http://html5demos.com/contenteditable.

Our production currently boasts an efficient solution that involves a form showing contact information enclosed within span tags. The form also includes an edit image, which when clicked, rotates the span tag to reveal an input text for making modifications. The JQuery Flip plugin is what we use to execute this functionality, resulting in a smooth and stylish end-product.

Create a HTML span as a text using java / javascript, I need to induce a style property (color) to a selected text in a html div. This html div is created dynamically and is not accessible as a DOM element. Is there a way to do this ? I have tried this : — inducing a html span (having the required style) along with the selected text.

Читайте также:  Php get url with params

Create a HTML span as a text using java / javascript

GWT offers the ability to generate a span-element and apply the desired style to it.

Something like this should work:

FlowPanel fp = new FlowPanel(); Element el = DOM.createSpan(); el.getStyle().setColor("orange"); el.setInnerHTML("add your data here . "); fp.getElement().appendChild(el); 

I opted for a FlowPanel as it is a basic div component.

The second quotation marks were left open by mistake.

String data="hello"; String sig= "its me !!"+"" + data + ""; widget.setData(sig); 

on the line where you assign sig

Javascript cannot parse certain special characters such as , «, /, ; that are used in the above statement. To replace them, one can make use of their corresponding hexadecimal character codes, such as \u0022 for «, \u003c for , and \u005c for \.

My code below may provide you with a hint.

var str = "hello"; var str2 = "its me !! "; var startTag = "\u003cspan style=\u0022color:orange;\u0022\u003e"; var endTag = "\u003c/script\u003e;"; console.log(str + " " + str2 + startTag + endTag); 

Wrap text with element using Javascript or jQuery, Then .insertAdjacentHTML() inserts the new span after deleting the old text node. Since I don’t know what the rest of your page looks like, I’ll assume there could be multiple elements, but the code will work either way.

How do to wrap a span around a section of text without using jQuery

To access the paragraph, you’ll require a specific attribute like «foo,» which can be represented as id .

Afterward, utilize document.getElementById to reach the element and modify its offspring as needed.

var p = document.getElementById('foo'), firstTextNode = p.firstChild, newSpan = document.createElement('span'); // Append "Lorem Ipsum" text to new span: newSpan.appendChild( document.createTextNode(firstTextNode.nodeValue) ); // Replace old text node with new span: p.replaceChild( newSpan, firstTextNode ); 

To enhance its dependability, it may be advisable to invoke p.normalize() prior to accessing the initial child, thereby ensuring the consolidation of all text nodes preceding the anchor.

Okay, you’re looking to substitute a portion of a text node with an element. This is how I would proceed:

function giveMeDOM(html) < var div = document.createElement('div'), frag = document.createDocumentFragment(); div.innerHTML = html; while (div.firstChild) < frag.appendChild( div.firstChild ); >return frag; > var p = document.getElementById('foo'), firstChild = p.firstChild; // Merge adjacent text nodes: p.normalize(); // Get new DOM structure: var newStructure = giveMeDOM( firstChild.nodeValue.replace(/Lorem Ipsum/i, '$&') ); // Replace first child with new DOM structure: p.replaceChild( newStructure, firstChild ); 

Dealing with nodes at a lower level can be unpleasant, particularly when you lack any assistance from abstractions. To maintain a sense of regularity, I transformed an HTML string, which replaced the «Lorem Ipsum» phrase, into a DOM node. Although this solution may not appeal to purists, I believe it is entirely appropriate.

Updated: Employing a document fragment now, with gratitude to Crescent Fresh!

The method described below involves searching the subtree that is headed by container and enclosing all occurrences of text with a span element. The words may be found in any location within a text node, and the text node itself may be situated at any point within the subtree. An update has been provided.

Читайте также:  Reading json file with javascript

(Pretty much, it required several adjustments, more than just minor ones. :P)

function wrapText(container, text) < // Construct a regular expression that matches text at the start or end of a string or surrounded by non-word characters. // Escape any special regex characters in text. var textRE = new RegExp('(^|\\W)' + text.replace(/[\\^$*+.?[\]<>()|]/, '\\$&') + '($|\\W)', 'm'); var nodeText; var nodeStack = []; // Remove empty text nodes and combine adjacent text nodes. container.normalize(); // Iterate through the container's child elements, looking for text nodes. var curNode = container.firstChild; while (curNode != null) < if (curNode.nodeType == Node.TEXT_NODE) < // Get node text in a cross-browser compatible fashion. if (typeof curNode.textContent == 'string') nodeText = curNode.textContent; else nodeText = curNode.innerText; // Use a regular expression to check if this text node contains the target text. var match = textRE.exec(nodeText); if (match != null) < // Create a document fragment to hold the new nodes. var fragment = document.createDocumentFragment(); // Create a new text node for any preceding text. if (match.index >0) fragment.appendChild(document.createTextNode(match.input.substr(0, match.index))); // Create the wrapper span and add the matched text to it. var spanNode = document.createElement('span'); spanNode.appendChild(document.createTextNode(match[0])); fragment.appendChild(spanNode); // Create a new text node for any following text. if (match.index + match[0].length < match.input.length) fragment.appendChild(document.createTextNode(match.input.substr(match.index + match[0].length))); // Replace the existing text node with the fragment. curNode.parentNode.replaceChild(fragment, curNode); curNode = spanNode; >> else if (curNode.nodeType == Node.ELEMENT_NODE && curNode.firstChild != null) < nodeStack.push(curNode); curNode = curNode.firstChild; // Skip the normal node advancement code. continue; >// If there's no more siblings at this level, pop back up the stack until we find one. while (curNode != null && curNode.nextSibling == null) curNode = nodeStack.pop(); // If curNode is null, that means we've completed our scan of the DOM tree. // If not, we need to advance to the next sibling. if (curNode != null) curNode = curNode.nextSibling; > > 

Combine these 2 tutorials:

PPK on JavaScript: The DOM — Part 3

To achieve the desired outcome, the approach involves extracting the node value, eliminating it, and establishing a fresh child component with the same value as the parent’s node. Then, the newly formed component (span, in this context) is attached to the parent element (paragraph, in this scenario).

Using span with javascript to create CSS transition, The span element has the red text style on creation. You are not transitioning an element from one style to another, you are simply inserting it with the redtext class style. What you need to do is add a span with black text inside it, and then change the class of the span from «blacktext» to «redtext», and the …

Источник

Оцените статью