You can create a max lenght for span, div or p

1

Hello, this is my question: I know there is an attribute for input and text-area with which the number of characters is manipulated as maxlenght , my question is if this can be done with span , div or any other label. My idea is to have something like:

<span maxlength="9">David Perez</span>

But on the screen ONLY shows:

David Per

If the solution is JQuery , JavaScript or CSS it does not matter I appreciate any help.

    
asked by CristianTAC 18.01.2017 в 23:21
source

2 answers

1

A simple way is to cut the character string, I do it with javascript. For example:

var substr;
var str = "cadena";

substr = str.substring(0, 3);
console.log(substr);

this as a result will print on the screen cad that only 3 characters are assigned to cut the string of characters and finally to print the data in the span just give it an id. For example:

html

<span id="nombre"> </span>

javascript

document.getElementById("nombre").innerHTML = substr;

the whole example:

<!DOCTYPE html>
<html>
<body>

<span id="nombre"> </span>

<button onclick="myFunction()">Imprimir cadena</button>

<script>
function myFunction() {
    var substr;
    var str = "cadena";

    substr = str.substring(0, 3);

    document.getElementById("nombre").innerHTML = substr;

}
</script>

</body>
</html>
    
answered by 19.01.2017 / 16:20
source
0

The maxlength attribute is only for the input and textarea tags. You can emulate the same with JavaScript in any component.

let btn = document.getElementById('cut');
btn.addEventListener('click', () => {
  let lines = document.querySelectorAll('.line');
  [].forEach.call(lines, line => applyMaxLen(line, 10));
});

function applyMaxLen (el, maxChars = 5) {
  el.textContent = el.textContent.substring(0, maxChars);
}
.line {
  border-bottom: 1px solid #eee;
  color: #333;
  display: block;
  height: 35px;
  line-height: 35px;
  padding: 0 .25rem;
}
#cut {
  margin-top: 20px;
}
<span class="line">Hola, ¿cómo estás?</span>
<span class="line">Bien, gracias, ¿y tú?</span>
<button id="cut">Cortar</button>
    
answered by 18.01.2017 в 23:32