Home > Software engineering >  How do I set some attributes e,g white space = nowrap to the url extracted from content before asign
How do I set some attributes e,g white space = nowrap to the url extracted from content before asign

Time:03-22

Any logic of setting attributes to a substring in javascript.

if (spanArr.length != 0) {
var span = document.createElement('span');
var content = spanArr.join(" ");
var url = content.match(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&= \$,\w] @)?[A-Za-z0-9.-] |(?:www.|[-;:&= \$,\w] @)[A-Za-z0-9.-] )((?:\/[ ~%\/.\w-]*)?\??(?:[- =&;%@.\w])#?(?:[\w]))?)/);

    span.textContent = ?;
    divContent.appendChild(span);
  }

How do I set some attributes e,g white space = nowrap to the url extracted from content before asigning it to span textContent.

CodePudding user response:

It seems you have a few concepts mixed up here.

white-space: nowrap is a CSS statement that, when applied to an HTML element, causes the text and any inline level elements inside that element to not wrap to the next line when the edge of the element is reached. This only applies to block level elements that have a width or otherwise do not have the option to expand to accomodate the content.

CSS attributes like white-space can only be applied to DOM Elements, not to strings (like your url). The url, in this case, would be the text content (in fact, the textContent) of the span element. The white-space would be a CSS attribute of the element.

CSS attributes can be applied to DOM elements in 3 ways: through CSS declarations in a <style> tag or external CSS file; though the HTML style attribute, or through direct manipulation in JavaScript of the related style property of a DOM HTMLElement.

Since you are working in JavaScript, you want to do the latter here. If I understand correctly what you are trying to do, the following code should get you what you want:

span.textContent = url;
span.style.whiteSpace = 'nowrap';
divContent.appendChild(span);

Note: in JavaScript the CSS properties of the style property are written in camelCase (with capitals in the middle of words) instead of kebab-case (with hyphens between words), because JavaScript would interpret the - character as an arithmetic operator if you were to use that.

Another note: the white-space applied to a span will probably not do a lot, since a span is not a block level element. If your goal is to make the spans not wrap within the divContent element, you should add the styling to that element instead:

divContent.style.whiteSpace = 'nowrap';
  • Related